/**
 * Marketing Channels Map Models
 *
 * MarketingChannel — individual marketing channels with metrics and touchpoints
 * ChannelMap — a complete channel map tying channels together with funnel visualization
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// CHANNEL TOUCHPOINT (Embedded Sub-document)
// ============================================

export type TouchpointType = 'ad' | 'email' | 'post' | 'page' | 'event' | 'call' | 'video' | 'other';
export type FunnelStage = 'awareness' | 'consideration' | 'conversion' | 'retention' | 'advocacy';
export type AudienceRole = 'decision-maker' | 'influencer' | 'end-user' | 'gatekeeper';

interface IChannelTouchpoint extends Document {
  name: string;
  type: TouchpointType;
  stage: FunnelStage;
  description?: string;
  url?: string;
  audienceRole?: AudienceRole;
  frequency?: string;
  budget?: number;
}

const ChannelTouchpointSchema = new Schema<IChannelTouchpoint>(
  {
    name: { type: String, required: true, trim: true },
    type: {
      type: String,
      enum: ['ad', 'email', 'post', 'page', 'event', 'call', 'video', 'other'],
      default: 'other',
    },
    stage: {
      type: String,
      enum: ['awareness', 'consideration', 'conversion', 'retention', 'advocacy'],
      required: true,
    },
    description: { type: String, trim: true },
    url: { type: String, trim: true },
    audienceRole: {
      type: String,
      enum: ['decision-maker', 'influencer', 'end-user', 'gatekeeper'],
    },
    frequency: { type: String, trim: true },
    budget: { type: Number, default: 0 },
  },
  { _id: true }
);

// ============================================
// CHANNEL METRICS (Embedded Sub-document)
// ============================================

interface IChannelMetrics extends Document {
  impressions?: number;
  clicks?: number;
  conversions?: number;
  revenue?: number;
  cpa?: number;
  ctr?: number;
}

const ChannelMetricsSchema = new Schema<IChannelMetrics>(
  {
    impressions: { type: Number, default: 0 },
    clicks: { type: Number, default: 0 },
    conversions: { type: Number, default: 0 },
    revenue: { type: Number, default: 0 },
    cpa: { type: Number, default: 0 },
    ctr: { type: Number, default: 0 },
  },
  { _id: false }
);

// ============================================
// MARKETING CHANNEL
// ============================================

export type ChannelType = 'social-media' | 'email' | 'seo' | 'ppc' | 'content' | 'pr' | 'events' | 'referral' | 'direct' | 'partnership' | 'influencer' | 'podcast' | 'video' | 'other';
export type ChannelStatus = 'active' | 'paused' | 'planned' | 'deprecated';
export type ChannelPriority = 'primary' | 'secondary' | 'experimental';

export interface IMarketingChannel extends Document {
  companyId: string;
  name: string;
  description?: string;
  channelType: ChannelType;
  platform?: string;
  funnelStages: FunnelStage[];
  targetAudienceRoles: AudienceRole[];
  budgetAllocated?: number;
  budgetSpent?: number;
  roi?: number;
  metrics?: IChannelMetrics;
  touchpoints?: IChannelTouchpoint[];
  status: ChannelStatus;
  priority: ChannelPriority;
  linkedContentIds?: string[];
  tags?: string[];
  aiGenerated?: boolean;
  aiStatus?: 'idle' | 'processing' | 'done' | 'error';
  notes?: string;
  createdAt: Date;
  updatedAt: Date;
}

const MarketingChannelSchema = new Schema<IMarketingChannel>(
  {
    companyId: {
      type: String,
      required: [true, 'Company ID is required'],
      index: true,
    },
    name: {
      type: String,
      required: [true, 'Name is required'],
      trim: true,
      maxlength: [200, 'Name cannot exceed 200 characters'],
    },
    description: {
      type: String,
      trim: true,
      maxlength: [1000, 'Description cannot exceed 1000 characters'],
    },
    channelType: {
      type: String,
      enum: ['social-media', 'email', 'seo', 'ppc', 'content', 'pr', 'events', 'referral', 'direct', 'partnership', 'influencer', 'podcast', 'video', 'other'],
      default: 'other',
    },
    platform: {
      type: String,
      trim: true,
      maxlength: [100, 'Platform cannot exceed 100 characters'],
    },
    funnelStages: {
      type: [String],
      enum: ['awareness', 'consideration', 'conversion', 'retention', 'advocacy'],
      default: [],
    },
    targetAudienceRoles: {
      type: [String],
      enum: ['decision-maker', 'influencer', 'end-user', 'gatekeeper'],
      default: [],
    },
    budgetAllocated: {
      type: Number,
      default: 0,
      min: [0, 'Budget Allocated cannot be negative'],
    },
    budgetSpent: {
      type: Number,
      default: 0,
      min: [0, 'Budget Spent cannot be negative'],
    },
    roi: {
      type: Number,
      default: 0,
      min: [0, 'ROI cannot be negative'],
    },
    metrics: {
      type: ChannelMetricsSchema,
      default: () => ({}),
    },
    touchpoints: {
      type: [ChannelTouchpointSchema],
      default: [],
    },
    status: {
      type: String,
      enum: ['active', 'paused', 'planned', 'deprecated'],
      default: 'planned',
    },
    priority: {
      type: String,
      enum: ['primary', 'secondary', 'experimental'],
      default: 'secondary',
    },
    linkedContentIds: {
      type: [String],
      default: [],
    },
    tags: {
      type: [String],
      default: [],
    },
    aiGenerated: {
      type: Boolean,
      default: false,
    },
    aiStatus: {
      type: String,
      enum: ['idle', 'processing', 'done', 'error'],
      default: 'idle',
    },
    notes: {
      type: String,
      trim: true,
      maxlength: [1000, 'Notes cannot exceed 1000 characters'],
    },
  },
  { timestamps: true }
);

MarketingChannelSchema.index({ companyId: 1, channelType: 1 });
MarketingChannelSchema.index({ companyId: 1, status: 1 });

export const MarketingChannel = mongoose.model<IMarketingChannel>('MarketingChannel', MarketingChannelSchema);

// ============================================
// CHANNEL MAP
// ============================================

export type ChannelMapStatus = 'draft' | 'active' | 'archived';

export interface IChannelMap extends Document {
  companyId: string;
  name: string;
  description?: string;
  channels: IMarketingChannel[];
  funnelVisualization?: FunnelStage[];
  totalBudget?: number;
  status: ChannelMapStatus;
  aiGenerated?: boolean;
  aiStatus?: 'idle' | 'processing' | 'done' | 'error';
  tags?: string[];
  createdAt: Date;
  updatedAt: Date;
}

const ChannelMapSchema = new Schema<IChannelMap>(
  {
    companyId: {
      type: String,
      required: [true, 'Company ID is required'],
      index: true,
    },
    name: {
      type: String,
      required: [true, 'Name is required'],
      trim: true,
      maxlength: [200, 'Name cannot exceed 200 characters'],
    },
    description: {
      type: String,
      trim: true,
    },
    channels: {
      type: [MarketingChannelSchema],
      default: [],
    },
    funnelVisualization: {
      type: [String],
      enum: ['awareness', 'consideration', 'conversion', 'retention', 'advocacy'],
      default: ['awareness', 'consideration', 'conversion', 'retention', 'advocacy'],
    },
    totalBudget: {
      type: Number,
      default: 0,
    },
    status: {
      type: String,
      enum: ['draft', 'active', 'archived'],
      default: 'draft',
    },
    aiGenerated: {
      type: Boolean,
      default: false,
    },
    aiStatus: {
      type: String,
      enum: ['idle', 'processing', 'done', 'error'],
      default: 'idle',
    },
    tags: {
      type: [String],
      default: [],
    },
  },
  { timestamps: true }
);

ChannelMapSchema.index({ companyId: 1, status: 1 });

export const ChannelMap = mongoose.model<IChannelMap>('ChannelMap', ChannelMapSchema);