/**
 * Google Ads App Config Model
 *
 * Platform-wide Google Ads API credentials for the Google Ads integration,
 * managed from Super Admin → Settings (no .env editing needed).
 * Stored as a singleton document with companyId = 'platform'. The Developer
 * Token, Client ID, Client Secret are AES-256-GCM encrypted at rest and excluded
 * from queries by default. Environment variables remain a fallback.
 *
 * Mirrors PinterestAppConfig / TwitterAppConfig / ThreadsAppConfig.
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface IGoogleAdsAppConfig extends Document {
  companyId: string;
  encryptedDeveloperToken?: string;
  developerTokenIV?: string;
  encryptedClientId?: string;
  clientIdIV?: string;
  encryptedClientSecret?: string;
  clientSecretIV?: string;
  redirectUrl: string;
  managerId: string;
  updatedBy: string;
  createdAt: Date;
  updatedAt: Date;
}

const GoogleAdsAppConfigSchema = new Schema<IGoogleAdsAppConfig>({
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true,
  },
  encryptedDeveloperToken: {
    type: String,
    select: false,
  },
  developerTokenIV: {
    type: String,
    select: false,
  },
  encryptedClientId: {
    type: String,
    select: false,
  },
  clientIdIV: {
    type: String,
    select: false,
  },
  encryptedClientSecret: {
    type: String,
    select: false,
  },
  clientSecretIV: {
    type: String,
    select: false,
  },
  redirectUrl: {
    type: String,
    default: '',
  },
  managerId: {
    type: String,
    default: '',
  },
  updatedBy: {
    type: String,
    required: true,
  },
}, {
  timestamps: true,
});

GoogleAdsAppConfigSchema.index({ companyId: 1 }, { unique: true });

export const GoogleAdsAppConfig = mongoose.models.GoogleAdsAppConfig || mongoose.model<IGoogleAdsAppConfig>('GoogleAdsAppConfig', GoogleAdsAppConfigSchema);