/**
 * Investor Model
 *
 * Investor CRM with pipeline stages, activity tracking, and AI email generation.
 */

import mongoose, { Schema, Document, models, Model } from 'mongoose';

// ============================================
// TYPES
// ============================================

export type InvestorStage = 'prospect' | 'introduced' | 'meeting' | 'due-diligence' | 'term-sheet' | 'closed' | 'passed';
export type InvestorType = 'angel' | 'seed-fund' | 'vc' | 'private-equity' | 'strategic' | 'accelerator' | 'family-office';
export type CheckSize = '10-50k' | '50-100k' | '100-250k' | '250-500k' | '500k-1m' | '1m-5m' | '5m-plus';
export type InvestorPriority = 'low' | 'medium' | 'high';

export interface IInvestmentThesis {
  sectors?: string[];
  stages?: string[];
  geographies?: string[];
  checkSizes?: CheckSize[];
  ticketRange?: { min: number; max: number };
  notes?: string;
}

export interface IInvestorInteraction {
  id: string;
  date: string;
  type: 'email' | 'call' | 'meeting' | 'video-call' | 'event' | 'intro';
  summary: string;
  outcome?: string;
  nextSteps?: string;
  attendees?: string[];
}

export interface ITermSheetData {
  valuation?: number;
  amount?: number;
  equity?: number;
  terms?: string;
  notes?: string;
}

export interface IWarmIntro {
  from: string;
  relationship: string;
  contactDate?: string;
}

export interface IInvestor extends Document {
  companyId: string;
  name: string;
  type: InvestorType;
  organization: string;
  title?: string;
  email: string;
  phone?: string;
  linkedin?: string;
  twitter?: string;
  website?: string;
  thesis: IInvestmentThesis;
  portfolioCompanies?: string[];
  notableInvestments?: string[];
  stage: InvestorStage;
  priority: InvestorPriority;
  lastContactDate?: string;
  nextFollowUpDate?: string;
  interactions: IInvestorInteraction[];
  termSheetData?: ITermSheetData;
  tags?: string[];
  notes?: string;
  warmIntros?: IWarmIntro[];
  source?: string;
  referredBy?: string;
  createdBy: string;
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SCHEMA
// ============================================

const InvestmentThesisSchema = new Schema<IInvestmentThesis>(
  {
    sectors: [{ type: String }],
    stages: [{ type: String }],
    geographies: [{ type: String }],
    checkSizes: [{
      type: String,
      enum: ['10-50k', '50-100k', '100-250k', '250-500k', '500k-1m', '1m-5m', '5m-plus'],
    }],
    ticketRange: {
      min: { type: Number },
      max: { type: Number },
    },
    notes: { type: String },
  },
  { _id: false }
);

const InvestorInteractionSchema = new Schema<IInvestorInteraction>(
  {
    id: { type: String, required: true },
    date: { type: String, required: true },
    type: {
      type: String,
      enum: ['email', 'call', 'meeting', 'video-call', 'event', 'intro'],
      required: true,
    },
    summary: { type: String, required: true },
    outcome: { type: String },
    nextSteps: { type: String },
    attendees: [{ type: String }],
  },
  { _id: false }
);

const TermSheetDataSchema = new Schema<ITermSheetData>(
  {
    valuation: { type: Number },
    amount: { type: Number },
    equity: { type: Number },
    terms: { type: String },
    notes: { type: String },
  },
  { _id: false }
);

const WarmIntroSchema = new Schema<IWarmIntro>(
  {
    from: { type: String, required: true },
    relationship: { type: String, required: true },
    contactDate: { type: String },
  },
  { _id: false }
);

const InvestorSchema = new Schema<IInvestor>(
  {
    companyId: { type: String, required: true, index: true },
    name: { type: String, required: true, maxlength: 200 },
    type: {
      type: String,
      enum: ['angel', 'seed-fund', 'vc', 'private-equity', 'strategic', 'accelerator', 'family-office'],
      required: true,
    },
    organization: { type: String, required: true, maxlength: 200 },
    title: { type: String, maxlength: 100 },
    email: { type: String, required: true, lowercase: true },
    phone: { type: String },
    linkedin: { type: String },
    twitter: { type: String },
    website: { type: String },
    thesis: { type: InvestmentThesisSchema, default: () => ({}) },
    portfolioCompanies: [{ type: String }],
    notableInvestments: [{ type: String }],
    stage: {
      type: String,
      enum: ['prospect', 'introduced', 'meeting', 'due-diligence', 'term-sheet', 'closed', 'passed'],
      default: 'prospect',
    },
    priority: {
      type: String,
      enum: ['low', 'medium', 'high'],
      default: 'medium',
    },
    lastContactDate: { type: String },
    nextFollowUpDate: { type: String },
    interactions: [InvestorInteractionSchema],
    termSheetData: TermSheetDataSchema,
    tags: [{ type: String }],
    notes: { type: String, maxlength: 5000 },
    warmIntros: [WarmIntroSchema],
    source: { type: String },
    referredBy: { type: String },
    createdBy: { type: String, required: true },
  },
  { timestamps: true }
);

// Indexes
InvestorSchema.index({ companyId: 1, stage: 1 });
InvestorSchema.index({ companyId: 1, priority: 1 });
InvestorSchema.index({ companyId: 1, 'thesis.sectors': 1 });
InvestorSchema.index({ companyId: 1, createdAt: -1 });
InvestorSchema.index({ companyId: 1, email: 1 }, { unique: false });

// ============================================
// MODEL
// ============================================

export const Investor: Model<IInvestor> =
  models.Investor || mongoose.model<IInvestor>('Investor', InvestorSchema);

export default Investor;