/**
 * Threads (Meta Threads) App Config Model
 *
 * Platform-wide Threads OAuth 2.0 app credentials for the Threads integration,
 * managed from Super Admin → Settings (no .env editing needed). Stored as a
 * singleton document with companyId = 'platform'. The Threads App ID and App
 * Secret are AES-256-GCM encrypted at rest and excluded from queries by default.
 * Environment variables remain a fallback.
 *
 * NOTE: Threads has its OWN app credentials (the "Threads" use case inside a
 * Meta app) and its own OAuth/Graph endpoints (graph.threads.net) — these are
 * NOT the shared Meta/Facebook app credentials that the Instagram integration
 * reuses. Hence a dedicated config, mirroring TwitterAppConfig / LinkedInAppConfig.
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface IThreadsAppConfig extends Document {
  companyId: string;
  encryptedClientId?: string;
  clientIdIV?: string;
  encryptedClientSecret?: string;
  clientSecretIV?: string;
  redirectUrl: string;
  graphVersion: string;
  scope: string;
  updatedBy: string;
  createdAt: Date;
  updatedAt: Date;
}

const ThreadsAppConfigSchema = new Schema<IThreadsAppConfig>({
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true,
  },
  encryptedClientId: {
    type: String,
    select: false,
  },
  clientIdIV: {
    type: String,
    select: false,
  },
  encryptedClientSecret: {
    type: String,
    select: false,
  },
  clientSecretIV: {
    type: String,
    select: false,
  },
  redirectUrl: {
    type: String,
    default: '',
  },
  graphVersion: {
    type: String,
    default: 'v1.0',
  },
  scope: {
    type: String,
    default: 'threads_basic,threads_content_publish',
  },
  updatedBy: {
    type: String,
    required: true,
  },
}, {
  timestamps: true,
});

ThreadsAppConfigSchema.index({ companyId: 1 }, { unique: true });

export const ThreadsAppConfig = mongoose.models.ThreadsAppConfig || mongoose.model<IThreadsAppConfig>('ThreadsAppConfig', ThreadsAppConfigSchema);
