/**
 * n8n Configuration Model
 *
 * Stores platform-wide n8n connection settings as a singleton document
 * (companyId: 'platform'). The API key is AES-256-GCM encrypted at rest
 * using the same encryption module as YouTubeAppConfig and GoogleDriveToken.
 *
 * The base URL and API key are managed by super admins in Super Admin → Settings.
 * The frontend never receives the raw API key — only a masked version.
 */

import mongoose, { Schema, Document } from 'mongoose';
import { encryptApiKey, decryptApiKey } from '../services/utils/encryption';

// ============================================
// TYPE DEFINITIONS
// ============================================

export type N8nConfigStatus = 'connected' | 'disconnected' | 'error';

export interface IN8nConfig extends Document {
  companyId: string;
  baseUrl: string;
  /** Encrypted API key — stored as "ciphertext:authTag" */
  encryptedApiKey?: string;
  /** IV for the encrypted API key */
  apiKeyIV?: string;
  /** Whether n8n integration is enabled */
  enabled: boolean;
  /** Last known connection status */
  status: N8nConfigStatus;
  /** n8n version string (populated on health check) */
  n8nVersion?: string;
  /** When the config was last validated */
  lastValidatedAt?: Date;
  /** Who created/updated the config */
  updatedBy?: string;
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// HELPER: Decrypt API key
// ============================================

/**
 * Decrypt the n8n API key from a config document.
 * Must use .select('+encryptedApiKey +apiKeyIV') to include the encrypted fields.
 */
export function decryptN8nApiKey(config: IN8nConfig): string | null {
  if (!config.encryptedApiKey || !config.apiKeyIV) return null;
  try {
    return decryptApiKey(config.encryptedApiKey, config.apiKeyIV);
  } catch (error) {
    console.error('[N8nConfig] Failed to decrypt API key:', error);
    return null;
  }
}

// ============================================
// MAIN SCHEMA
// ============================================

const N8nConfigSchema = new Schema<IN8nConfig>({
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    default: 'platform',
    unique: true,
  },
  baseUrl: {
    type: String,
    required: [true, 'Base URL is required'],
    default: 'http://localhost:5678',
  },
  encryptedApiKey: {
    type: String,
    select: false,
  },
  apiKeyIV: {
    type: String,
    select: false,
  },
  enabled: {
    type: Boolean,
    default: false,
  },
  status: {
    type: String,
    enum: ['connected', 'disconnected', 'error'],
    default: 'disconnected',
  },
  n8nVersion: {
    type: String,
  },
  lastValidatedAt: {
    type: Date,
  },
  updatedBy: {
    type: String,
  },
}, {
  timestamps: true,
});

// ============================================
// INDEXES
// ============================================

N8nConfigSchema.index({ companyId: 1 }, { unique: true });

// ============================================
// EXPORT
// ============================================

export const N8nConfig = mongoose.models.N8nConfig || mongoose.model<IN8nConfig>('N8nConfig', N8nConfigSchema);