import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Schema as MongooseSchema, Types } from 'mongoose';

export enum LeadStage {
    NEW = 'NEW',
    IN_DISCUSSION = 'IN_DISCUSSION',
    QUOTATION_SHARED = 'QUOTATION_SHARED',
    CONVERTED = 'CONVERTED',
    LOST = 'LOST'
}

export const OPEN_STAGES = [LeadStage.NEW, LeadStage.IN_DISCUSSION, LeadStage.QUOTATION_SHARED];

export enum LeadHistoryType {
    EVENT = 'EVENT', // system entry, translated from `action` on read
    NOTE = 'NOTE',   // remark typed by a person, shown as written
    CALL = 'CALL'    // remark that also logs a call
}

const LeadHistorySchema = new MongooseSchema({
    type: { type: String, enum: Object.values(LeadHistoryType), required: true },
    action: { type: String, default: null },
    text: { type: String, default: null },
    meta: { type: MongooseSchema.Types.Mixed, default: null },
    actor_id: { type: MongooseSchema.Types.ObjectId, default: null },
    actor_name: { type: String, default: null },
    created_at: { type: Number, default: () => +new Date() }
}, { _id: false });

@Schema({
    timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
})
export class Lead extends Document {
    @Prop({ type: Types.ObjectId, ref: 'customers', required: true, index: true })
    customer_id: Types.ObjectId;

    @Prop({ type: Types.ObjectId, ref: 'categories', required: true })
    category_id: Types.ObjectId;

    @Prop({ type: Types.ObjectId, ref: 'users', required: true, index: true })
    assigned_to: Types.ObjectId;

    @Prop({ type: String, enum: LeadStage, default: LeadStage.NEW, index: true })
    stage: LeadStage;

    @Prop({ type: Number, default: null, min: 0 })
    estimated_premium: number;

    @Prop({ type: String, default: null, trim: true })
    notes: string; // requirement notes captured with the lead

    @Prop({ type: String, default: null })
    lost_reason: string;

    @Prop({ type: Number, default: null })
    last_call_at: number;

    @Prop({ type: Number, default: null })
    next_follow_up_at: number;

    @Prop({ type: Number, default: null })
    converted_at: number;

    @Prop({ type: Types.ObjectId, ref: 'policies', default: null })
    policy_id: Types.ObjectId; // set when the lead is converted

    @Prop({ type: Types.ObjectId, ref: 'users', default: null })
    created_by: Types.ObjectId;

    @Prop({ type: [LeadHistorySchema], default: [] })
    history: { type: string; action: string; text: string; meta: any; actor_id: any; actor_name: string; created_at: number }[];
}

export const LeadSchema = SchemaFactory.createForClass(Lead);
