/**
 * Meta Ads App Config Model
 *
 * Platform-wide Meta (Facebook) Marketing API credentials for the Meta Ads
 * integration, managed from Super Admin → Settings (no .env editing needed).
 * Stored as a singleton document with companyId = 'platform'. The App ID and
 * App Secret are AES-256-GCM encrypted at rest and excluded from queries by
 * default. Environment variables remain a fallback.
 *
 * Mirrors GoogleAdsAppConfig / PinterestAppConfig / FacebookAppConfig.
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface IMetaAdsAppConfig extends Document {
  companyId: string;
  encryptedAppId?: string;
  appIdIV?: string;
  encryptedAppSecret?: string;
  appSecretIV?: string;
  redirectUrl: string;
  graphVersion: string;
  businessManagerId: string;
  updatedBy: string;
  createdAt: Date;
  updatedAt: Date;
}

const MetaAdsAppConfigSchema = new Schema<IMetaAdsAppConfig>({
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true,
  },
  encryptedAppId: {
    type: String,
    select: false,
  },
  appIdIV: {
    type: String,
    select: false,
  },
  encryptedAppSecret: {
    type: String,
    select: false,
  },
  appSecretIV: {
    type: String,
    select: false,
  },
  redirectUrl: {
    type: String,
    default: '',
  },
  graphVersion: {
    type: String,
    default: 'v21.0',
  },
  businessManagerId: {
    type: String,
    default: '',
  },
  updatedBy: {
    type: String,
    required: true,
  },
}, {
  timestamps: true,
});

MetaAdsAppConfigSchema.index({ companyId: 1 }, { unique: true });

export const MetaAdsAppConfig = mongoose.models.MetaAdsAppConfig || mongoose.model<IMetaAdsAppConfig>('MetaAdsAppConfig', MetaAdsAppConfigSchema);