/**
 * EmailIntegration Model
 *
 * Stores email provider connection details per company.
 * API keys are encrypted using AES-256-GCM and never exposed to frontend.
 *
 * Supported providers:
 * - Brevo: API key authentication
 * - Zoho Campaigns: OAuth 2.0 authentication (access token + refresh token)
 * - Future: Mailchimp, SendGrid, MailerLite, SES
 *
 * Multi-tenant support:
 * - Platform-level credentials (env vars): Use for shared OAuth app
 * - Company-level credentials: Each company uses their own OAuth app
 */

import mongoose, { Schema, Document } from 'mongoose';

export type EmailProvider = 'brevo' | 'zoho' | 'mailchimp' | 'sendgrid' | 'mailerlite' | 'ses';
export type ConnectionStatus = 'disconnected' | 'connected' | 'error' | 'pending_verification';

export interface IEmailIntegration extends Document {
  companyId: string;
  provider: EmailProvider;

  // Encrypted credentials (never exposed to frontend)
  // For Brevo: API key
  // For Zoho: Access token
  encryptedApiKey: string;
  encryptionIV: string;

  // Zoho OAuth 2.0 specific fields
  encryptedRefreshToken?: string;  // Encrypted refresh token (Zoho only)
  refreshTokenIV?: string;          // IV for refresh token encryption
  tokenExpiresAt?: Date;            // Access token expiry time
  zohoDataCenter?: string;          // Data center code: 'com', 'eu', 'in', 'au', 'jp', etc.
  zohoAccountsServer?: string;     // Full URL: 'https://accounts.zoho.com'

  // Company-level OAuth credentials (for multi-tenant where each company has their own app)
  // These override platform-level credentials
  zohoClientId?: string;           // Encrypted Zoho Client ID
  zohoClientIdIV?: string;          // IV for Client ID encryption
  zohoClientSecret?: string;        // Encrypted Zoho Client Secret
  zohoClientSecretIV?: string;      // IV for Client Secret encryption

  // Connection status
  status: ConnectionStatus;
  lastVerifiedAt?: Date;
  errorMessage?: string;

  // Account metadata (safe to expose)
  accountEmail?: string;
  accountName?: string;
  accountPlan?: string;

  // Sender configuration
  defaultSenderId?: number;
  defaultSenderEmail?: string;
  defaultSenderName?: string;

  // Webhook configuration
  webhookId?: string;
  webhookUrl?: string;
  webhookEvents?: string[];

  // Per-company webhook verification secret (encrypted).
  // Appended as ?token=... on the registered provider webhook URL and
  // verified on inbound webhooks so a spoofed ?companyId= call is rejected.
  webhookSecret?: string;   // Encrypted token ("ciphertext:authTag")
  webhookSecretIV?: string; // IV for the encrypted token

  // Sync tracking
  lastContactSyncAt?: Date;
  lastCampaignSyncAt?: Date;

  // Timestamps
  createdAt: Date;
  updatedAt: Date;
}

const EmailIntegrationSchema = new Schema<IEmailIntegration>(
  {
    companyId: {
      type: String,
      required: [true, 'Company ID is required'],
      index: true,
    },
    provider: {
      type: String,
      enum: ['brevo', 'zoho', 'mailchimp', 'sendgrid', 'mailerlite', 'ses'],
      default: 'brevo',
    },
    encryptedApiKey: {
      type: String,
      required: [true, 'Encrypted API key is required'],
      select: false,
    },
    encryptionIV: {
      type: String,
      required: [true, 'Encryption IV is required'],
      select: false,
    },
    // Zoho OAuth 2.0 specific fields
    encryptedRefreshToken: {
      type: String,
      select: false,
    },
    refreshTokenIV: {
      type: String,
      select: false,
    },
    tokenExpiresAt: Date,
    zohoDataCenter: String,
    zohoAccountsServer: String,
    // Company-level OAuth credentials
    zohoClientId: {
      type: String,
      select: false,
    },
    zohoClientIdIV: {
      type: String,
      select: false,
    },
    zohoClientSecret: {
      type: String,
      select: false,
    },
    zohoClientSecretIV: {
      type: String,
      select: false,
    },
    status: {
      type: String,
      enum: ['disconnected', 'connected', 'error', 'pending_verification'],
      default: 'disconnected',
    },
    lastVerifiedAt: Date,
    errorMessage: String,
    accountEmail: String,
    accountName: String,
    accountPlan: String,
    defaultSenderId: Number,
    defaultSenderEmail: String,
    defaultSenderName: String,
    webhookId: String,
    webhookUrl: String,
    webhookEvents: [String],
    webhookSecret: {
      type: String,
      select: false,
    },
    webhookSecretIV: {
      type: String,
      select: false,
    },
    lastContactSyncAt: Date,
    lastCampaignSyncAt: Date,
  },
  { timestamps: true }
);

// Compound unique index for companyId + provider (allows multiple providers per company)
EmailIntegrationSchema.index({ companyId: 1, provider: 1 }, { unique: true });
// Index for quick lookup by company
EmailIntegrationSchema.index({ companyId: 1 });

export const EmailIntegration = mongoose.model<IEmailIntegration>(
  'EmailIntegration',
  EmailIntegrationSchema
);