/**
 * X (Twitter) App Config Model
 *
 * Platform-wide X (Twitter) OAuth 2.0 app credentials for the X integration,
 * managed from Super Admin → Settings (no .env editing needed). Stored as a
 * singleton document with companyId = 'platform'. Client ID and Client Secret
 * are AES-256-GCM encrypted at rest and excluded from queries by default.
 * Environment variables remain a fallback.
 *
 * `scope` lets a super admin control the requested OAuth scopes. X v2 is not
 * date-versioned (unlike LinkedIn), so there is no apiVersion field.
 *
 * Mirrors LinkedInAppConfig / YouTubeAppConfig / FacebookAppConfig.
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface ITwitterAppConfig extends Document {
  companyId: string;
  encryptedClientId?: string;
  clientIdIV?: string;
  encryptedClientSecret?: string;
  clientSecretIV?: string;
  redirectUrl: string;
  scope: string;
  updatedBy: string;
  createdAt: Date;
  updatedAt: Date;
}

const TwitterAppConfigSchema = new Schema<ITwitterAppConfig>({
  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: '',
  },
  scope: {
    type: String,
    default: 'tweet.read tweet.write users.read offline.access media.write',
  },
  updatedBy: {
    type: String,
    required: true,
  },
}, {
  timestamps: true,
});

TwitterAppConfigSchema.index({ companyId: 1 }, { unique: true });

export const TwitterAppConfig = mongoose.models.TwitterAppConfig || mongoose.model<ITwitterAppConfig>('TwitterAppConfig', TwitterAppConfigSchema);
