/**
 * AdCampaign Model
 * Campaign management for the Ads Management System
 */

import mongoose, { Document, Schema } from 'mongoose';

// ============================================
// TYPES
// ============================================

export type AdCampaignStatus = 'draft' | 'active' | 'paused' | 'completed' | 'archived';
export type AdCampaignGoal = 'awareness' | 'traffic' | 'leads' | 'conversions' | 'engagement' | 'app-installs' | 'video-views' | 'retargeting';
export type AdPlatformType = 'meta' | 'google';
export type BudgetType = 'campaign' | 'adset';
export type BudgetPeriod = 'daily' | 'lifetime';
export type BuyingType = 'AUCTION' | 'RESERVED' | 'MIXED';
export type CampaignSubtype = 'SEARCH' | 'DISPLAY' | 'SHOPPING' | 'VIDEO' | 'APP';
export type AdPlatform =
  | 'google-search'
  | 'google-display'
  | 'google-shopping'
  | 'facebook'
  | 'instagram'
  | 'tiktok'
  | 'linkedin'
  | 'youtube'
  | 'twitter'
  | 'pinterest'
  | 'snapchat'
  | 'reddit'
  | 'microsoft';

export interface IAdSchedule {
  startDate: string;
  endDate?: string;
  dayParting?: {
    monday?: string[];
    tuesday?: string[];
    wednesday?: string[];
    thursday?: string[];
    friday?: string[];
    saturday?: string[];
    sunday?: string[];
  };
}

export interface IAdCampaign extends Document {
  companyId: string;
  name: string;
  description?: string;
  goal: AdCampaignGoal;
  status: AdCampaignStatus;
  platforms: AdPlatform[];
  platformType?: AdPlatformType;
  budgetType?: BudgetType;
  budgetPeriod?: BudgetPeriod;
  buyingType?: BuyingType;
  campaignSubtype?: CampaignSubtype;
  startDate: string;
  endDate?: string;
  totalBudget: number;
  currency?: string;
  schedule?: IAdSchedule;
  audienceId?: string;
  notes?: string;
  tags?: string[];
  color?: string;
  specialAdCategories?: string[];
  // Google Ads specific fields
  googleCampaignChannel?: string;
  googleCampaignObjective?: string;
  googleCampaignType?: string;
  googleWaysToReachGoal?: string[];
  googleWaysWebsiteUrl?: string;
  googleWaysPhoneNumber?: string;
  googleWaysPhoneCountryCode?: string;
  googleWaysStoreAddresses?: string[];
  googleBiddingStrategy?: string;
  googleTargetCpa?: number;
  googleTargetCpc?: number;
  googleTargetRoas?: number;
  googleTargetImpressionShare?: number;
  googleNetworks?: string[];
  googleLocations?: string[];
  googleLanguages?: string[];
  googleEuPoliticalAds?: boolean;
  googleAudienceSegments?: string[];
  googleAudienceTargetingMode?: string;
  googleAiMax?: {
    enabled: boolean;
    assetOptimization?: boolean;
    textCustomization?: boolean;
    finalUrlExpansion?: boolean;
    brandInclusions?: string[];
    brandExclusions?: string[];
  };
  googleBudgetType?: string;
  googleBudgetAmount?: number;
  googleFinalUrl?: string;
  googleUniqueSellingPoints?: string[];
  googleKeywordGenerationSkipped?: boolean;
  googleDisplayImages?: string[];
  googlePmaxImages?: string[];
  googlePmaxVideos?: string[];
  googleVideoImages?: string[];
  googleVideoVideos?: string[];
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SUB-SCHEMAS
// ============================================

const DayPartingSchema = new Schema({
  monday: [{ type: String }],
  tuesday: [{ type: String }],
  wednesday: [{ type: String }],
  thursday: [{ type: String }],
  friday: [{ type: String }],
  saturday: [{ type: String }],
  sunday: [{ type: String }],
}, { _id: false });

const AdScheduleSchema = new Schema<IAdSchedule>({
  startDate: { type: String, required: true },
  endDate: { type: String },
  dayParting: { type: DayPartingSchema },
}, { _id: false });

// ============================================
// MAIN SCHEMA
// ============================================

const AdCampaignSchema = new Schema<IAdCampaign>({
  companyId: { type: String, required: [true, 'Company ID is required'] },
  name: { type: String, required: [true, 'Campaign name is required'], trim: true },
  description: { type: String, trim: true },
  goal: {
    type: String,
    enum: ['awareness', 'traffic', 'leads', 'conversions', 'engagement', 'app-installs', 'video-views', 'retargeting'],
    required: [true, 'Campaign goal is required'],
    default: 'awareness',
  },
  status: {
    type: String,
    enum: ['draft', 'active', 'paused', 'completed', 'archived'],
    default: 'draft',
  },
  platforms: [{
    type: String,
    enum: ['google-search', 'google-display', 'google-shopping', 'facebook', 'instagram', 'tiktok', 'linkedin', 'youtube', 'twitter', 'pinterest', 'snapchat', 'reddit', 'microsoft'],
  }],
  startDate: { type: String, required: [true, 'Start date is required'] },
  endDate: { type: String },
  totalBudget: { type: Number, default: 0 },
  currency: { type: String, default: 'USD' },
  schedule: { type: AdScheduleSchema },
  audienceId: { type: String },
  notes: { type: String, trim: true },
  tags: [{ type: String }],
  color: { type: String },
  specialAdCategories: [{ type: String }], // Meta special ad categories: CREDIT, EMPLOYMENT, HOUSING, ISSUES_ELECTIONS_POLITICS

  // Wizard-specific fields
  platformType: { type: String, enum: ['meta', 'google'] },
  budgetType: { type: String, enum: ['campaign', 'adset'] },
  budgetPeriod: { type: String, enum: ['daily', 'lifetime'] },
  buyingType: { type: String, enum: ['AUCTION', 'RESERVED', 'MIXED'] },
  campaignSubtype: { type: String, enum: ['SEARCH', 'DISPLAY', 'SHOPPING', 'VIDEO', 'APP'] },

  // Google Ads specific fields
  googleCampaignChannel: { type: String },
  googleCampaignObjective: { type: String },
  googleCampaignType: { type: String },
  googleWaysToReachGoal: [{ type: String }],
  googleWaysWebsiteUrl: { type: String },
  googleWaysPhoneNumber: { type: String },
  googleWaysPhoneCountryCode: { type: String },
  googleWaysStoreAddresses: [{ type: String }],
  googleBiddingStrategy: { type: String },
  googleTargetCpa: { type: Number },
  googleTargetCpc: { type: Number },
  googleTargetRoas: { type: Number },
  googleTargetImpressionShare: { type: Number },
  googleNetworks: [{ type: String }],
  googleLocations: [{ type: String }],
  googleLanguages: [{ type: String }],
  googleEuPoliticalAds: { type: Boolean, default: false },
  googleAudienceSegments: [{ type: String }],
  googleAudienceTargetingMode: { type: String },
  googleAiMax: {
    enabled: { type: Boolean, default: false },
    assetOptimization: { type: Boolean, default: false },
    textCustomization: { type: Boolean, default: false },
    finalUrlExpansion: { type: Boolean, default: false },
    brandInclusions: [{ type: String }],
    brandExclusions: [{ type: String }],
  },
  googleBudgetType: { type: String },
  googleBudgetAmount: { type: Number },
  googleFinalUrl: { type: String },
  googleUniqueSellingPoints: [{ type: String }],
  googleKeywordGenerationSkipped: { type: Boolean, default: false },
  googleDisplayImages: [{ type: String }],
  googlePmaxImages: [{ type: String }],
  googlePmaxVideos: [{ type: String }],
  googleVideoImages: [{ type: String }],
  googleVideoVideos: [{ type: String }],
}, { timestamps: true, toJSON: { virtuals: true }, toObject: { virtuals: true } });

// Indexes
AdCampaignSchema.index({ companyId: 1, status: 1 });
AdCampaignSchema.index({ companyId: 1, platforms: 1 });
AdCampaignSchema.index({ companyId: 1, startDate: 1 });

export const AdCampaign = mongoose.model<IAdCampaign>('AdCampaign', AdCampaignSchema);