/**
 * Facebook App Config Model
 *
 * Platform-wide Facebook (Meta) OAuth app credentials for the Facebook
 * integration, managed from Super Admin → Settings (no .env editing needed).
 * Stored as a singleton document with companyId = 'platform'. App ID and App
 * Secret are AES-256-GCM encrypted at rest and excluded from queries by
 * default. Environment variables (FACEBOOK_APP_ID / FACEBOOK_APP_SECRET)
 * remain a fallback.
 *
 * Mirrors YouTubeAppConfig.
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface IFacebookAppConfig extends Document {
  companyId: string;
  encryptedAppId?: string;
  appIdIV?: string;
  encryptedAppSecret?: string;
  appSecretIV?: string;
  redirectUrl: string;
  graphVersion: string;
  updatedBy: string;
  createdAt: Date;
  updatedAt: Date;
}

const FacebookAppConfigSchema = new Schema<IFacebookAppConfig>({
  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',
  },
  updatedBy: {
    type: String,
    required: true,
  },
}, {
  timestamps: true,
});

FacebookAppConfigSchema.index({ companyId: 1 }, { unique: true });

export const FacebookAppConfig = mongoose.models.FacebookAppConfig || mongoose.model<IFacebookAppConfig>('FacebookAppConfig', FacebookAppConfigSchema);
