/**
 * Email Designer Template Model
 *
 * Stores visually-designed email templates created in the template builder.
 * Each template contains blocks (visual layout) and design settings,
 * along with a rendered htmlOutput for use by the automation engine.
 *
 * This model bridges the template builder UI (/newsletter-content-os/templates)
 * and the automation workflow engine's "Send Email" node.
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// TYPES
// ============================================

export type EmailDesignerTemplateStatus = 'draft' | 'published' | 'archived';

export interface IEmailBlock {
  id: string;
  type: string;
  data: Record<string, any>;
}

export interface IEmailDesignSettings {
  subject: string;
  previewText: string;
  senderName: string;
  replyToEmail: string;
  category: string;
  tags: string[];
  backgroundColor: string;
  contentBackgroundColor: string;
  contentWidth: number;
  fontFamily: string;
  preheaderText?: string;
}

export interface IEmailDesignerTemplate extends Document {
  companyId: string;
  name: string;
  slug: string;
  subject: string;
  previewText: string;
  senderName: string;
  replyToEmail: string;
  category: string;
  tags: string[];
  blocks: any[];  // Stored as Mixed — frontend blocks have varying shapes
  designSettings: IEmailDesignSettings;
  htmlOutput: string;
  status: EmailDesignerTemplateStatus;
  version: number;
  createdById?: string;
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SCHEMA
// ============================================

// Blocks are stored as Mixed to preserve all frontend block properties
// (text, fontSize, color, padding, etc.) without needing to define every
// possible field in a rigid schema. The frontend EmailBlock types define
// the shape; the backend just needs to store and retrieve them faithfully.
// We keep a thin validation schema for the array itself.

const EmailDesignSettingsSchema = new Schema({
  subject: { type: String, default: '' },
  previewText: { type: String, default: '' },
  senderName: { type: String, default: '' },
  replyToEmail: { type: String, default: '' },
  category: { type: String, default: '' },
  tags: [{ type: String }],
  backgroundColor: { type: String, default: '#1a1d21' },
  contentBackgroundColor: { type: String, default: '#ffffff' },
  contentWidth: { type: Number, default: 600 },
  fontFamily: { type: String, default: 'Arial, sans-serif' },
  preheaderText: { type: String },
}, { _id: false });

const EmailDesignerTemplateSchema = new Schema<IEmailDesignerTemplate>(
  {
    companyId: {
      type: String,
      required: [true, 'Company ID is required'],
      index: true,
    },
    name: {
      type: String,
      required: [true, 'Template name is required'],
      trim: true,
      maxlength: [200, 'Name cannot exceed 200 characters'],
    },
    slug: {
      type: String,
      trim: true,
      lowercase: true,
    },
    subject: {
      type: String,
      trim: true,
      maxlength: [200, 'Subject cannot exceed 200 characters'],
    },
    previewText: {
      type: String,
      trim: true,
      maxlength: [200, 'Preview text cannot exceed 200 characters'],
    },
    senderName: {
      type: String,
      trim: true,
    },
    replyToEmail: {
      type: String,
      trim: true,
    },
    category: {
      type: String,
      trim: true,
      default: '',
    },
    tags: [{
      type: String,
      trim: true,
    }],
    blocks: {
      type: [{ type: Schema.Types.Mixed }],
      default: [],
    },
    designSettings: {
      type: EmailDesignSettingsSchema,
      default: () => ({}),
    },
    htmlOutput: {
      type: String,
      default: '',
    },
    status: {
      type: String,
      enum: ['draft', 'published', 'archived'],
      default: 'draft',
    },
    version: {
      type: Number,
      default: 1,
    },
    createdById: {
      type: String,
    },
  },
  { timestamps: true }
);

// Indexes
EmailDesignerTemplateSchema.index({ companyId: 1, status: 1 });
EmailDesignerTemplateSchema.index({ companyId: 1, category: 1 });
EmailDesignerTemplateSchema.index({ companyId: 1, slug: 1 });

// Auto-generate slug from name
EmailDesignerTemplateSchema.pre('save', function (next) {
  const doc = this as any;
  if (!doc.slug && doc.name) {
    const base = doc.name
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-|-$/g, '')
      .substring(0, 80);
    const suffix = Date.now().toString(36).slice(-4);
    doc.slug = `${base}-${suffix}`;
  }
  next();
});

export const EmailDesignerTemplate = mongoose.models.EmailDesignerTemplate || mongoose.model('EmailDesignerTemplate', EmailDesignerTemplateSchema);