/**
 * Executive CV Model
 * Stores AI-generated executive CVs for founders
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// TYPES
// ============================================

export type CVStatus = 'draft' | 'completed' | 'archived';

export interface IProfessionalExperience {
  id: string;
  company: string;
  role: string;
  employmentType?: 'full-time' | 'part-time' | 'contract' | 'freelance' | 'internship' | 'co-founder';
  industry?: string;
  location?: string;
  startDate: string;
  endDate?: string;
  isCurrent: boolean;
  description?: string;
  achievements: string[];
  skills: string[];
  responsibilities?: string[];
}

export interface IEducation {
  id: string;
  institution: string;
  degree: string;
  field?: string;
  startYear: string;
  endYear?: string;
  isCurrent?: boolean;
  grade?: string;
  achievements?: string[];
  location?: string;
  description?: string;
}

export interface ICVProject {
  id: string;
  name: string;
  description: string;
  role: string;
  startDate?: string;
  endDate?: string;
  isCurrent: boolean;
  outcomes: string[];
  technologies?: string[];
  teamSize?: number;
  budget?: string;
  businessImpact?: string;
  // Reference to Products module (optional import)
  productId?: string;
  source: 'imported' | 'manual';
}

export interface IInterviewMedia {
  id: string;
  type: 'podcast' | 'tv' | 'media-interview' | 'panel-discussion';
  title: string;
  platform?: string;
  date: string;
  description?: string;
  link?: string;
  highlights?: string[];
}

export interface ISpeakingEngagementCV {
  id: string;
  title: string;
  event: string;
  date: string;
  type: 'keynote' | 'conference' | 'workshop' | 'guest-lecture' | 'panel';
  audience?: string;
  description?: string;
  recordingUrl?: string;
}

export interface IFundingHighlight {
  id: string;
  roundType: string;
  amount: string;
  date: string;
  investors: string[];
  milestone?: string;
}

export interface IPresentationHighlight {
  id: string;
  title: string;
  type: string;
  date: string;
  audience?: string;
  description?: string;
  link?: string;
}

export interface IGeneratedCV {
  personalInfo: {
    name: string;
    designation: string;
    bio: string;
    email: string;
    phone?: string;
    website?: string;
    linkedin?: string;
    photo?: string;
    otherSocials?: Record<string, string>;
  };
  executiveSummary: string;
  experience: IProfessionalExperience[];
  projects: ICVProject[];
  skills: string[];
  achievements: string[];
  education?: {
    institution: string;
    degree: string;
    year: string;
    field?: string;
  }[];
  certifications?: {
    name: string;
    issuer: string;
    year: string;
  }[];
  mediaPresence: {
    interviews: IInterviewMedia[];
    speaking: ISpeakingEngagementCV[];
  };
  fundingTrackRecord: IFundingHighlight[];
  presentations: IPresentationHighlight[];
}

export interface IDataSourceSelections {
  founder: boolean;
  businessProfile: boolean;
  interviewMedia: string[];
  speakingEngagements: string[];
  fundingRounds: string[];
  presentations: string[];
}

export interface IExecutiveCV extends Document {
  companyId: string;
  founderId: string;
  status: CVStatus;

  // Profile photo (separate storage from Founder)
  profilePhoto?: string;

  // Data source selections
  dataSourceSelections: IDataSourceSelections;

  // Wizard step completion tracking
  completedSteps: string[];
  currentStep: 'data-sources' | 'experience' | 'projects' | 'review';

  // Manual entries
  professionalExperience: IProfessionalExperience[];
  education: IEducation[];
  manualProjects: ICVProject[];

  // AI-generated CV content
  generatedCV?: IGeneratedCV;

  // AI prompt context (for regeneration)
  promptContext?: string;

  // Version tracking
  version: number;
  previousVersions?: {
    version: number;
    generatedCV: IGeneratedCV;
    savedAt: Date;
    savedBy: string;
  }[];

  createdBy: string;
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SCHEMAS
// ============================================

const ProfessionalExperienceSchema = new Schema<IProfessionalExperience>({
  id: { type: String, required: true },
  company: { type: String, required: true },
  role: { type: String, required: true },
  employmentType: {
    type: String,
    enum: ['full-time', 'part-time', 'contract', 'freelance', 'internship', 'co-founder']
  },
  industry: String,
  location: String,
  startDate: { type: String, required: true },
  endDate: String,
  isCurrent: { type: Boolean, default: false },
  description: String,
  achievements: [{ type: String }],
  skills: [{ type: String }],
  responsibilities: [{ type: String }],
}, { _id: false });

const EducationSchema = new Schema<IEducation>({
  id: { type: String, required: true },
  institution: { type: String, required: true },
  degree: { type: String, required: true },
  field: String,
  startYear: { type: String, required: true },
  endYear: String,
  isCurrent: { type: Boolean, default: false },
  grade: String,
  achievements: [{ type: String }],
  location: String,
  description: String,
}, { _id: false });

const CVProjectSchema = new Schema<ICVProject>({
  id: { type: String, required: true },
  name: { type: String, required: true },
  description: { type: String, required: true },
  role: { type: String, required: true },
  startDate: String,
  endDate: String,
  isCurrent: { type: Boolean, default: false },
  outcomes: [{ type: String }],
  technologies: [{ type: String }],
  teamSize: Number,
  budget: String,
  businessImpact: String,
  productId: String,
  source: {
    type: String,
    enum: ['imported', 'manual'],
    required: true
  },
}, { _id: false });

const InterviewMediaSchema = new Schema<IInterviewMedia>({
  id: { type: String, required: true },
  type: {
    type: String,
    enum: ['podcast', 'tv', 'media-interview', 'panel-discussion'],
    required: true
  },
  title: { type: String, required: true },
  platform: String,
  date: { type: String, required: true },
  description: String,
  link: String,
  highlights: [{ type: String }],
}, { _id: false });

const SpeakingEngagementCVSchema = new Schema<ISpeakingEngagementCV>({
  id: { type: String, required: true },
  title: { type: String, required: true },
  event: { type: String, required: true },
  date: { type: String, required: true },
  type: {
    type: String,
    enum: ['keynote', 'conference', 'workshop', 'guest-lecture', 'panel'],
    required: true
  },
  audience: String,
  description: String,
  recordingUrl: String,
}, { _id: false });

const FundingHighlightSchema = new Schema<IFundingHighlight>({
  id: { type: String, required: true },
  roundType: { type: String, required: true },
  amount: { type: String, required: true },
  date: { type: String, required: true },
  investors: [{ type: String }],
  milestone: String,
}, { _id: false });

const PresentationHighlightSchema = new Schema<IPresentationHighlight>({
  id: { type: String, required: true },
  title: { type: String, required: true },
  type: { type: String, required: true },
  date: { type: String, required: true },
  audience: String,
  description: String,
  link: String,
}, { _id: false });

const GeneratedCVSchema = new Schema<IGeneratedCV>({
  personalInfo: {
    name: { type: String, required: true },
    designation: { type: String, required: true },
    bio: { type: String, required: true },
    // Optional, like the founder record it comes from: `Founder.email` is not a
    // mandatory field, so requiring it here rejected every generated CV for a
    // founder without an email — after the AI call had already succeeded.
    email: { type: String, default: '' },
    phone: { type: String, default: '' },
    website: { type: String, default: '' },
    linkedin: { type: String, default: '' },
    photo: { type: String, default: '' },
    otherSocials: { type: Schema.Types.Mixed, default: {} },
  },
  executiveSummary: { type: String, required: true },
  experience: [ProfessionalExperienceSchema],
  projects: [CVProjectSchema],
  skills: [{ type: String }],
  achievements: [{ type: String }],
  education: [{
    institution: { type: String, required: true },
    degree: { type: String, required: true },
    year: { type: String, required: true },
    field: String,
    _id: false,
  }],
  certifications: [{
    name: { type: String, required: true },
    issuer: { type: String, required: true },
    year: { type: String, required: true },
    _id: false,
  }],
  mediaPresence: {
    interviews: [InterviewMediaSchema],
    speaking: [SpeakingEngagementCVSchema],
    _id: false,
  },
  fundingTrackRecord: [FundingHighlightSchema],
  presentations: [PresentationHighlightSchema],
}, { _id: false });

const DataSourceSelectionsSchema = new Schema<IDataSourceSelections>({
  founder: { type: Boolean, default: true },
  businessProfile: { type: Boolean, default: false },
  interviewMedia: [{ type: String }],
  speakingEngagements: [{ type: String }],
  fundingRounds: [{ type: String }],
  presentations: [{ type: String }],
}, { _id: false });

const PreviousVersionSchema = new Schema({
  version: { type: Number, required: true },
  generatedCV: { type: GeneratedCVSchema, required: true },
  savedAt: { type: Date, required: true },
  savedBy: { type: String, required: true },
}, { _id: false });

// ============================================
// MAIN SCHEMA
// ============================================

const ExecutiveCVSchema = new Schema<IExecutiveCV>({
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true
  },
  founderId: {
    type: String,
    required: [true, 'Founder ID is required'],
    index: true
  },
  status: {
    type: String,
    enum: ['draft', 'completed', 'archived'],
    default: 'draft'
  },

  profilePhoto: String,

  dataSourceSelections: {
    type: DataSourceSelectionsSchema,
    default: () => ({
      founder: true,
      businessProfile: false,
      interviewMedia: [],
      speakingEngagements: [],
      fundingRounds: [],
      presentations: []
    })
  },

  completedSteps: [{ type: String }],
  currentStep: {
    type: String,
    enum: ['data-sources', 'experience', 'projects', 'review'],
    default: 'data-sources'
  },

  professionalExperience: [ProfessionalExperienceSchema],
  education: [EducationSchema],
  manualProjects: [CVProjectSchema],

  generatedCV: { type: GeneratedCVSchema },
  promptContext: String,

  version: { type: Number, default: 1 },
  previousVersions: [PreviousVersionSchema],

  createdBy: { type: String, required: true },
}, {
  timestamps: true,
  toJSON: {
    virtuals: true,
    transform: (_doc, ret) => {
      ret.id = ret._id?.toString?.() || ret._id;
      return ret;
    }
  },
  toObject: {
    virtuals: true
  }
});

// Compound index for efficient queries
ExecutiveCVSchema.index({ companyId: 1, founderId: 1 });
ExecutiveCVSchema.index({ companyId: 1, status: 1 });

export const ExecutiveCV = mongoose.model<IExecutiveCV>('ExecutiveCV', ExecutiveCVSchema);