/**
 * tenant_email_templates — email-template-editor (wave-11 leaf-E).
 *
 * Per-tenant customizable email templates. When a row exists for
 * (tenant_id, template_key), it overrides the system default.
 *
 * template_key CHECK + UNIQUE(tenant_id, template_key) enforced in migration SQL.
 * The composite unique index is a GIN/partial equivalent → raw SQL only.
 */
import { pgTable, uuid, text, boolean, timestamp, uniqueIndex } from 'drizzle-orm/pg-core'
import { tenants } from './tenants'

export const tenantEmailTemplates = pgTable(
  'tenant_email_templates',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    tenantId: uuid('tenant_id')
      .notNull()
      .references(() => tenants.id, { onDelete: 'cascade' }),
    // CHECK (template_key IN (...)) enforced in migration SQL
    templateKey: text('template_key').notNull(),
    subject: text('subject').notNull(),
    bodyHtml: text('body_html').notNull(),
    bodyText: text('body_text').notNull(),
    isActive: boolean('is_active').notNull().default(true),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => ({
    tenantKeyUniq: uniqueIndex('idx_tenant_email_templates_key').on(t.tenantId, t.templateKey),
  }),
)

export type TenantEmailTemplateRow = typeof tenantEmailTemplates.$inferSelect
export type NewTenantEmailTemplate = typeof tenantEmailTemplates.$inferInsert
