/**
 * Blogger App Config Model
 *
 * Platform-wide Google OAuth app credentials for the Blogger 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.
 *
 * Mirrors YouTubeAppConfig (Google-based providers use ClientId naming).
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface IBloggerAppConfig extends Document {
  companyId: string;
  encryptedClientId?: string;
  clientIdIV?: string;
  encryptedClientSecret?: string;
  clientSecretIV?: string;
  redirectUrl: string;
  scopes: string;
  updatedBy: string;
  createdAt: Date;
  updatedAt: Date;
}

const BloggerAppConfigSchema = new Schema<IBloggerAppConfig>({
  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: '',
  },
  scopes: {
    type: String,
    default: 'https://www.googleapis.com/auth/blogger https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email',
  },
  updatedBy: {
    type: String,
    required: true,
  },
}, {
  timestamps: true,
});

BloggerAppConfigSchema.index({ companyId: 1 }, { unique: true });

export const BloggerAppConfig = mongoose.models.BloggerAppConfig || mongoose.model<IBloggerAppConfig>('BloggerAppConfig', BloggerAppConfigSchema);