/**
 * Payment Gateway Configuration Model
 * Stores Stripe and Razorpay API keys (global singleton, super-admin only).
 * Keys are stored encrypted in the database.
 */

import mongoose, { Schema, Document } from 'mongoose';

export type GatewayMode = 'sandbox' | 'live';

export interface IStripeConfig {
  publishableKey?: string;
  secretKey?: string;
  webhookSecret?: string;
  mode: GatewayMode;
}

export interface IRazorpayConfig {
  keyId?: string;
  keySecret?: string;
  webhookSecret?: string;
  mode: GatewayMode;
}

export interface IPaymentGatewayConfig extends Document {
  stripe: IStripeConfig;
  razorpay: IRazorpayConfig;
  updatedAt: Date;
}

const StripeConfigSchema = new Schema<IStripeConfig>({
  publishableKey: { type: String, default: '' },
  secretKey: { type: String, default: '' },
  webhookSecret: { type: String, default: '' },
  mode: { type: String, enum: ['sandbox', 'live'], default: 'sandbox' },
}, { _id: false });

const RazorpayConfigSchema = new Schema<IRazorpayConfig>({
  keyId: { type: String, default: '' },
  keySecret: { type: String, default: '' },
  webhookSecret: { type: String, default: '' },
  mode: { type: String, enum: ['sandbox', 'live'], default: 'sandbox' },
}, { _id: false });

const PaymentGatewayConfigSchema = new Schema<IPaymentGatewayConfig>({
  stripe: {
    type: StripeConfigSchema,
    default: () => ({ mode: 'sandbox' }),
  },
  razorpay: {
    type: RazorpayConfigSchema,
    default: () => ({ mode: 'sandbox' }),
  },
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true },
});

// Singleton pattern — ensure only one config document exists
PaymentGatewayConfigSchema.index({ createdAt: 1 });

export const PaymentGatewayConfig = mongoose.models.PaymentGatewayConfig || mongoose.model<IPaymentGatewayConfig>('PaymentGatewayConfig', PaymentGatewayConfigSchema);