import mongoose, { Document, Model, Schema } from 'mongoose';
import { encryptSecret, decryptSecret } from '@/lib/security';

export interface IStripeSettings {
  mode: 'test' | 'live';
  isEnabled: boolean;
  // Test mode keys
  testPublishableKey: string;
  testSecretKeyEncrypted?: string;
  // Live mode keys
  livePublishableKey: string;
  liveSecretKeyEncrypted?: string;
  // Legacy / fallback fields
  publishableKey?: string;
  secretKeyEncrypted?: string;
}

export interface IPaypalSettings {
  mode: 'test' | 'live';
  isEnabled: boolean;
  // Test mode credentials
  testClientId: string;
  testClientSecretEncrypted?: string;
  // Live mode credentials
  liveClientId: string;
  liveClientSecretEncrypted?: string;
  // Legacy / fallback fields
  clientId?: string;
  clientSecretEncrypted?: string;
}

export interface IBankTransferSettings {
  bankName: string;
  accountHolder: string;
  iban: string;
  bicSwift?: string;
  paymentInstructions: string;
  // paymentScreenshot?: string;
  paymentScreenShot?: string;
  isEnabled: boolean;
}

export interface ILegalPages {
  privacyPolicy: string;
  termsAndConditions: string;
}

export interface ISettings extends Document {
  isSingleton: boolean;
  stripe: IStripeSettings;
  paypal: IPaypalSettings;
  bankTransfer: IBankTransferSettings;
  defaultCourseExpiryMonths: number;
  defaultCourseExpiryDays: number;
  legalPages: ILegalPages;
  lastUpdatedBy?: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

const StripeSettingsSchema = new Schema<IStripeSettings>(
  {
    mode: {
      type: String,
      enum: ['test', 'live'],
      default: 'test',
    },
    isEnabled: {
      type: Boolean,
      default: true,
    },
    testPublishableKey: {
      type: String,
      trim: true,
      default: '',
    },
    testSecretKeyEncrypted: {
      type: String,
      trim: true,
      default: '',
    },
    livePublishableKey: {
      type: String,
      trim: true,
      default: '',
    },
    liveSecretKeyEncrypted: {
      type: String,
      trim: true,
      default: '',
    },
    // Legacy fields mapped for safety
    publishableKey: {
      type: String,
      trim: true,
      default: '',
    },
    secretKeyEncrypted: {
      type: String,
      trim: true,
      default: '',
    },
  },
  { _id: false }
);

const PaypalSettingsSchema = new Schema<IPaypalSettings>(
  {
    mode: {
      type: String,
      enum: ['test', 'live'],
      default: 'test',
    },
    isEnabled: {
      type: Boolean,
      default: true,
    },
    testClientId: {
      type: String,
      trim: true,
      default: '',
    },
    testClientSecretEncrypted: {
      type: String,
      trim: true,
      default: '',
    },
    liveClientId: {
      type: String,
      trim: true,
      default: '',
    },
    liveClientSecretEncrypted: {
      type: String,
      trim: true,
      default: '',
    },
    // Legacy fields
    clientId: {
      type: String,
      trim: true,
      default: '',
    },
    clientSecretEncrypted: {
      type: String,
      trim: true,
      default: '',
    },
  },
  { _id: false }
);

const BankTransferSettingsSchema = new Schema<IBankTransferSettings>(
  {
    bankName: {
      type: String,
      trim: true,
      default: '',
    },
    accountHolder: {
      type: String,
      trim: true,
      default: '',
    },
    iban: {
      type: String,
      trim: true,
      default: '',
    },
    bicSwift: {
      type: String,
      trim: true,
      default: '',
    },
    paymentInstructions: {
      type: String,
      default: 'Please transfer the course fee to our bank account and upload your receipt screenshot in checkout.',
    },
    // paymentScreenshot: {
    //   type: String,
    //   trim: true,
    //   default: '',
    // },
    paymentScreenShot: {
      type: String,
      trim: true,
      default: '',
    },
    isEnabled: {
      type: Boolean,
      default: true,
    },
  },
  { _id: false }
);

const LegalPagesSchema = new Schema<ILegalPages>(
  {
    privacyPolicy: {
      type: String,
      default: '# Privacy Policy\n\nApkaGermanSchool protects your personal data...',
    },
    termsAndConditions: {
      type: String,
      default: '# Terms & Conditions\n\nAll courses and video content are copyrighted by ApkaGermanSchool...',
    },
  },
  { _id: false }
);

const SettingsSchema: Schema<ISettings> = new Schema(
  {
    isSingleton: {
      type: Boolean,
      default: true,
      unique: true,
    },
    stripe: {
      type: StripeSettingsSchema,
      default: () => ({}),
    },
    paypal: {
      type: PaypalSettingsSchema,
      default: () => ({}),
    },
    bankTransfer: {
      type: BankTransferSettingsSchema,
      default: () => ({}),
    },
    defaultCourseExpiryMonths: {
      type: Number,
      default: 4,
      min: [0, 'Default expiry months cannot be negative'],
    },
    defaultCourseExpiryDays: {
      type: Number,
      default: 0,
      min: [0, 'Default expiry days cannot be negative'],
    },
    legalPages: {
      type: LegalPagesSchema,
      default: () => ({}),
    },
    lastUpdatedBy: {
      type: Schema.Types.ObjectId,
      ref: 'Admin',
    },
  },
  {
    timestamps: true,
  }
);

// Helper static to get or initialize the singleton settings document
SettingsSchema.statics.getSettings = async function (): Promise<ISettings> {
  let settings = await this.findOne({ isSingleton: true });
  if (!settings) {
    settings = await this.create({ isSingleton: true });
  }
  return settings;
};

export interface ISettingsModel extends Model<ISettings> {
  getSettings(): Promise<ISettings>;
}

export const Settings: ISettingsModel =
  (mongoose.models.Settings as ISettingsModel) ||
  mongoose.model<ISettings, ISettingsModel>('Settings', SettingsSchema);

export default Settings;
