/**
 * WhatsApp App Config Model
 *
 * Platform-wide WhatsApp Business API (Meta Cloud API) credentials for the
 * WhatsApp 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 remain a fallback.
 *
 * Mirors MetaAdsAppConfig / FacebookAppConfig.
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface IWhatsAppAppConfig extends Document {
  companyId: string;
  encryptedAppId?: string;
  appIdIV?: string;
  encryptedAppSecret?: string;
  appSecretIV?: string;
  webhookVerifyToken: string;
  webhookBaseUrl: string;
  embeddedSignupConfigId: string;
  graphVersion: string;
  businessManagerId: string;
  updatedBy: string;
  createdAt: Date;
  updatedAt: Date;
}

const WhatsAppAppConfigSchema = new Schema<IWhatsAppAppConfig>({
  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,
  },
  webhookVerifyToken: {
    type: String,
    default: '',
  },
  webhookBaseUrl: {
    type: String,
    default: '',
  },
  embeddedSignupConfigId: {
    type: String,
    default: '',
  },
  graphVersion: {
    type: String,
    default: 'v21.0',
  },
  businessManagerId: {
    type: String,
    default: '',
  },
  updatedBy: {
    type: String,
    required: true,
  },
}, {
  timestamps: true,
});

WhatsAppAppConfigSchema.index({ companyId: 1 }, { unique: true });

export const WhatsAppAppConfig = mongoose.models.WhatsAppAppConfig || mongoose.model<IWhatsAppAppConfig>('WhatsAppAppConfig', WhatsAppAppConfigSchema);