/**
 * Proposal Model
 * Manages proposals, quotes, SOWs, and estimates with line items,
 * discounting, approval workflows, and AI generation context.
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// TYPE DEFINITIONS
// ============================================

export type ProposalType = 'proposal' | 'quote' | 'sow' | 'estimate' | 'renewal' | 'amendment';

export type ProposalStatus = 'draft' | 'sent' | 'viewed' | 'negotiation' | 'accepted' | 'rejected' | 'expired' | 'cancelled';

export type DiscountType = 'percentage' | 'flat';

export interface IProposalLineItem extends Document {
  id: string;
  name: string;
  description: string;
  quantity: number;
  unitPrice: number;
  discount: number;
  total: number;
  category: string;
  productId: string;
}

export interface IProposalAiContext {
  pipelineVersion?: string;
  provider?: string;
  model?: string;
  confidence?: number;
  generatedAt?: Date;
}

export interface IProposal extends Document {
  companyId: string;
  title: string;
  description?: string;
  type: ProposalType;
  status: ProposalStatus;
  clientName: string;
  clientEmail?: string;
  clientCompany?: string;
  clientId?: string;
  assignedTo: string;
  assignedToName?: string;
  currency: string;
  subtotal?: number;
  discountType?: DiscountType;
  discountValue?: number;
  taxRate?: number;
  totalAmount?: number;
  lineItems: IProposalLineItem[];
  validUntil?: string;
  sentDate?: string;
  viewedDate?: string;
  acceptedDate?: string;
  rejectedDate?: string;
  terms?: string;
  internalNotes?: string;
  clientNotes?: string;
  productIds: string[];
  icpIds: string[];
  playbookId?: string;
  collateralIds: string[];
  approvedBy?: string;
  approvedAt?: Date;
  aiGenerated?: boolean;
  aiGenerationContext?: IProposalAiContext;
  version: number;
  isFavorite: boolean;
  tags: string[];

  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SUB-SCHEMAS
// ============================================

const ProposalLineItemSchema = new Schema<IProposalLineItem>(
  {
    id: { type: String, required: true },
    name: { type: String, required: true },
    description: { type: String, default: '' },
    quantity: { type: Number, default: 1 },
    unitPrice: { type: Number, default: 0 },
    discount: { type: Number, default: 0 },
    total: { type: Number, default: 0 },
    category: { type: String, trim: true },
    productId: { type: String },
  },
  { _id: false }
);

const ProposalAiContextSchema = new Schema<IProposalAiContext>(
  {
    pipelineVersion: { type: String },
    provider: { type: String },
    model: { type: String },
    confidence: { type: Number },
    generatedAt: { type: Date },
  },
  { _id: false }
);

// ============================================
// MAIN SCHEMA
// ============================================

const ProposalSchema = new Schema<IProposal>(
  {
    companyId: {
      type: String,
      required: [true, 'Company ID is required'],
      index: true,
    },
    title: {
      type: String,
      required: [true, 'Title is required'],
      trim: true,
    },
    description: { type: String, trim: true },
    type: {
      type: String,
      enum: ['proposal', 'quote', 'sow', 'estimate', 'renewal', 'amendment'],
      default: 'proposal',
    },
    status: {
      type: String,
      enum: ['draft', 'sent', 'viewed', 'negotiation', 'accepted', 'rejected', 'expired', 'cancelled'],
      default: 'draft',
    },
    clientName: {
      type: String,
      required: [true, 'Client name is required'],
      trim: true,
    },
    clientEmail: { type: String, trim: true },
    clientCompany: { type: String, trim: true },
    clientId: { type: String },
    assignedTo: {
      type: String,
      required: [true, 'Assigned to is required'],
    },
    assignedToName: { type: String, trim: true },
    currency: { type: String, default: 'USD' },
    subtotal: { type: Number },
    discountType: {
      type: String,
      enum: ['percentage', 'flat'],
    },
    discountValue: { type: Number },
    taxRate: { type: Number },
    totalAmount: { type: Number },
    lineItems: { type: [ProposalLineItemSchema], default: [] },
    validUntil: { type: String },
    sentDate: { type: String },
    viewedDate: { type: String },
    acceptedDate: { type: String },
    rejectedDate: { type: String },
    terms: { type: String, trim: true },
    internalNotes: { type: String, trim: true },
    clientNotes: { type: String, trim: true },
    productIds: { type: [String], default: [] },
    icpIds: { type: [String], default: [] },
    playbookId: { type: String },
    collateralIds: { type: [String], default: [] },
    approvedBy: { type: String },
    approvedAt: { type: Date },
    aiGenerated: { type: Boolean, default: false },
    aiGenerationContext: { type: ProposalAiContextSchema },
    version: { type: Number, default: 1 },
    isFavorite: { type: Boolean, default: false },
    tags: { type: [String], default: [] },
  },
  { timestamps: true }
);

// Indexes
ProposalSchema.index({ companyId: 1, status: 1 });
ProposalSchema.index({ companyId: 1, type: 1 });
ProposalSchema.index({ companyId: 1, assignedTo: 1 });

export const Proposal = mongoose.models.Proposal || mongoose.model<IProposal>('Proposal', ProposalSchema);