/**
 * WhatsApp Connection Model
 *
 * Stores per-admin WhatsApp Business Account (WABA) connections for the
 * WhatsApp Nurturing module. Mirrors FacebookAccount: a WhatsAppConnection
 * is scoped to (companyId, userId, phoneNumberId) so each admin connects and
 * manages their own WABA independently — no cross-admin access.
 *
 * The Embedded Signup flow returns a permanent (system user) access token for
 * the WABA + phone number. Both the access token and any refresh token are
 * encrypted at rest (AES-256-GCM via services/utils/encryption) and excluded
 * from queries by default (select:false).
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// TYPE DEFINITIONS
// ============================================

export type WhatsAppConnectionStatus = 'connected' | 'reconnect_required' | 'revoked';

// ============================================
// MAIN INTERFACE
// ============================================

export interface IWhatsAppConnection extends Document {
  companyId: string;
  userId: string; // owning admin — all access is scoped to this user
  wabaId: string; // WhatsApp Business Account ID
  wabaName?: string; // WABA display name
  phoneNumberId: string; // Phone number ID for sending messages
  phoneNumber?: string; // Display phone number (e.g. +1 555-0123)
  phoneNumberDisplayName?: string; // Quality rating / verified name
  // Encrypted token material — never returned by default queries
  encryptedAccessToken?: string;
  accessTokenIV?: string;
  encryptedRefreshToken?: string; // refresh token (if applicable)
  refreshTokenIV?: string;
  tokenExpiresAt?: Date; // null = permanent token
  scope: string;
  status: WhatsAppConnectionStatus;
  isDemo: boolean;
  connectedAt: Date;
  lastUsedAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// MAIN SCHEMA
// ============================================

const WhatsAppConnectionSchema = new Schema<IWhatsAppConnection>({
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true,
  },
  userId: {
    type: String,
    required: [true, 'User ID is required'],
    index: true,
  },
  wabaId: {
    type: String,
    required: [true, 'WABA ID is required'],
  },
  wabaName: {
    type: String,
    default: '',
  },
  phoneNumberId: {
    type: String,
    required: [true, 'Phone number ID is required'],
  },
  phoneNumber: {
    type: String,
    default: '',
  },
  phoneNumberDisplayName: {
    type: String,
    default: '',
  },
  // Encrypted token material — never returned by default queries
  encryptedAccessToken: {
    type: String,
    select: false,
  },
  accessTokenIV: {
    type: String,
    select: false,
  },
  encryptedRefreshToken: {
    type: String,
    select: false,
  },
  refreshTokenIV: {
    type: String,
    select: false,
  },
  tokenExpiresAt: {
    type: Date,
    default: null,
  },
  scope: {
    type: String,
    default: '',
  },
  status: {
    type: String,
    enum: ['connected', 'reconnect_required', 'revoked'],
    default: 'connected',
  },
  isDemo: {
    type: Boolean,
    default: false,
  },
  connectedAt: {
    type: Date,
    default: Date.now,
  },
  lastUsedAt: {
    type: Date,
    default: null,
  },
}, {
  timestamps: true,
});

// ============================================
// INDEXES
// ============================================

// One connection per admin per phone number per company — the isolation anchor
WhatsAppConnectionSchema.index({ companyId: 1, userId: 1, phoneNumberId: 1 }, { unique: true });
WhatsAppConnectionSchema.index({ companyId: 1, userId: 1 });
WhatsAppConnectionSchema.index({ phoneNumberId: 1 }); // webhook routing lookup

// ============================================
// EXPORT
// ============================================

export const WhatsAppConnection = mongoose.models.WhatsAppConnection || mongoose.model<IWhatsAppConnection>('WhatsAppConnection', WhatsAppConnectionSchema);