/**
 * LinkedIn App Config Model
 *
 * Platform-wide LinkedIn OAuth app credentials for the LinkedIn 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 — the default
 * is member-only publishing (self-serve); org scopes are added once the
 * Community Management API product is approved.
 *
 * Mirrors YouTubeAppConfig / FacebookAppConfig.
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface ILinkedInAppConfig extends Document {
  companyId: string;
  encryptedClientId?: string;
  clientIdIV?: string;
  encryptedClientSecret?: string;
  clientSecretIV?: string;
  redirectUrl: string;
  apiVersion: string;
  scope: string;
  updatedBy: string;
  createdAt: Date;
  updatedAt: Date;
}

const LinkedInAppConfigSchema = new Schema<ILinkedInAppConfig>({
  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: '',
  },
  apiVersion: {
    type: String,
    default: '202401',
  },
  scope: {
    type: String,
    default: 'openid profile email w_member_social',
  },
  updatedBy: {
    type: String,
    required: true,
  },
}, {
  timestamps: true,
});

LinkedInAppConfigSchema.index({ companyId: 1 }, { unique: true });

export const LinkedInAppConfig = mongoose.models.LinkedInAppConfig || mongoose.model<ILinkedInAppConfig>('LinkedInAppConfig', LinkedInAppConfigSchema);
