/**
 * Newsletter Template Model
 *
 * Stores ready-made newsletter designs managed from the Super Admin panel
 * (Email Templates → Newsletter tab). Each record is email-safe, table-based
 * HTML carrying `{{token}}` merge fields, plus the token values used to render
 * it.
 *
 * Deliberately separate from `EmailTemplate` for the same reason
 * `SignatureTemplate` is: that model's `type`/`category` are strict enums, its
 * `subjectLine` is required, and the Super Admin Email Templates list queries by
 * companyId with no type filter — so newsletter records stored there would
 * surface in that list.
 *
 * Mirrors `SignatureTemplate` field-for-field (string `companyId` tenant
 * scoping, `timestamps`, `toJSON` transform surfacing `id`) plus the two fields
 * a newsletter needs that a signature does not: `subjectLine` and `previewText`.
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// TYPES
// ============================================

export type NewsletterTemplateStatus = 'draft' | 'published' | 'archived';

export interface INewsletterTemplate extends Document {
  companyId: string;
  name: string;

  /** Key of the built-in design this record was seeded from (e.g. 'weekly-bloom'). */
  designKey?: string;

  /**
   * Id of the Super Admin record this one was copied from.
   *
   * Set only on company-scoped copies made from the Email Templates module's
   * Newsletters tab. It is what lets that tab pair a company's edited version
   * with the platform original, and what makes "Reset to original" possible —
   * the copy is deleted and the super-admin record shows through again
   * untouched. Mirrors the same field on `SignatureTemplate`.
   */
  sourceTemplateId?: string;

  /** Free-form grouping shown in the listing filter (e.g. 'editorial'). */
  category: string;

  /** Default subject line for sends built from this design. */
  subjectLine: string;

  /** Inbox preview snippet shown after the subject line. */
  previewText: string;

  /** Email-safe HTML with {{token}} merge fields preserved. */
  html: string;

  /** Values for the {{token}} merge fields, keyed by token name. */
  fieldValues: Record<string, string>;

  status: NewsletterTemplateStatus;
  tags: string[];

  createdBy: string;
  updatedBy?: string;
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SCHEMA
// ============================================

const NewsletterTemplateSchema = new Schema<INewsletterTemplate>({
  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'],
  },
  designKey: { type: String, trim: true, default: '' },
  sourceTemplateId: { type: String, trim: true, default: '' },
  category: { type: String, trim: true, default: 'general' },
  subjectLine: {
    type: String,
    trim: true,
    default: '',
    maxlength: [300, 'Subject line cannot exceed 300 characters'],
  },
  previewText: {
    type: String,
    trim: true,
    default: '',
    maxlength: [300, 'Preview text cannot exceed 300 characters'],
  },
  html: {
    type: String,
    required: [true, 'Newsletter HTML is required'],
    // Newsletters are full-page layouts, so they run considerably larger than a
    // signature block — the cap is raised accordingly.
    maxlength: [500000, 'Newsletter HTML too large'],
  },
  // Mixed: the token set evolves with the designs, so it is intentionally open.
  fieldValues: { type: Schema.Types.Mixed, default: {} },
  status: {
    type: String,
    enum: ['draft', 'published', 'archived'],
    default: 'draft',
  },
  tags: [{ type: String, trim: true }],

  createdBy: {
    type: String,
    required: [true, 'Created by is required'],
  },
  updatedBy: String,
}, {
  timestamps: true,
  toJSON: {
    virtuals: true,
    transform: (_doc, ret) => {
      ret.id = ret._id?.toString?.() || ret._id;
      return ret;
    },
  },
  toObject: {
    virtuals: true,
  },
});

NewsletterTemplateSchema.index({ companyId: 1, category: 1 });
NewsletterTemplateSchema.index({ companyId: 1, status: 1 });
NewsletterTemplateSchema.index({ companyId: 1, designKey: 1 });
NewsletterTemplateSchema.index({ companyId: 1, sourceTemplateId: 1 });

export const NewsletterTemplate =
  mongoose.models.NewsletterTemplate ||
  mongoose.model<INewsletterTemplate>('NewsletterTemplate', NewsletterTemplateSchema);
