/**
 * Product/Service Catalog schema — marketing-catalogs-campaigns (wave-9 leaf 3).
 * wave-11 leaf C additions (public-catalog-page):
 *  - catalog_shares: shareable public tokens pointing to a catalog template
 *  - catalog_templates: tenant catalog content templates with sections
 * Postgres / Neon via Hyperdrive.
 *
 * Tables:
 *  - catalog_items: per-tenant product/service catalog with pricing
 *  - catalog_templates: named content templates (sections JSONB)
 *  - catalog_shares: public share tokens linking to a template
 *
 * Enum-like columns use text() + CHECK constraints, never pgEnum.
 * JSONB columns use jsonb().
 * Plain btree indexes via drizzle index().
 * Partial/expression indexes in raw_ddl (manifest).
 */
import {
  pgTable,
  uuid,
  text,
  boolean,
  numeric,
  jsonb,
  timestamp,
  index,
  uniqueIndex,
} from 'drizzle-orm/pg-core'
import { tenants } from './tenants'

// ── catalog_items ─────────────────────────────────────────────────────────────

export const catalogItems = pgTable(
  'catalog_items',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    tenantId: uuid('tenant_id').notNull(),
    name: text('name').notNull(),
    description: text('description'),
    sku: text('sku'),
    unitPrice: numeric('unit_price', { precision: 12, scale: 2 }).notNull(),
    currency: text('currency').notNull().default('ILS'),
    unit: text('unit').default('unit'),
    category: text('category'),
    isActive: boolean('is_active').notNull().default(true),
    metadata: jsonb('metadata'),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => ({
    tenantIdx: index('idx_catalog_items_tenant').on(t.tenantId),
    tenantCategoryIdx: index('idx_catalog_items_tenant_category').on(t.tenantId, t.category),
  }),
)

export type CatalogItemRow = typeof catalogItems.$inferSelect
export type NewCatalogItem = typeof catalogItems.$inferInsert

// ── catalog_templates ─────────────────────────────────────────────────────────

export const catalogTemplates = pgTable(
  'catalog_templates',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    tenantId: uuid('tenant_id')
      .notNull()
      .references(() => tenants.id, { onDelete: 'cascade' }),
    name: text('name').notNull(),
    // Structured sections: hero | text | products | pricing_table | cta | gallery
    content: jsonb('content').notNull().default({}),
    isActive: boolean('is_active').notNull().default(true),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => ({
    tenantIdx: index('idx_catalog_templates_tenant').on(t.tenantId),
  }),
)

export type CatalogTemplateRow = typeof catalogTemplates.$inferSelect
export type NewCatalogTemplate = typeof catalogTemplates.$inferInsert

// ── catalog_shares ────────────────────────────────────────────────────────────

export const catalogShares = pgTable(
  'catalog_shares',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    tenantId: uuid('tenant_id')
      .notNull()
      .references(() => tenants.id, { onDelete: 'cascade' }),
    templateId: uuid('template_id')
      .notNull()
      .references(() => catalogTemplates.id, { onDelete: 'cascade' }),
    // Opaque public token — URL-safe, globally unique
    publicToken: text('public_token').notNull().unique(),
    isActive: boolean('is_active').notNull().default(true),
    settings: jsonb('settings').notNull().default({}),
    // UTM attribution captured at share creation
    utmSource: text('utm_source'),
    utmMedium: text('utm_medium'),
    utmCampaign: text('utm_campaign'),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => ({
    tenantIdx: index('idx_catalog_shares_tenant').on(t.tenantId),
    publicTokenIdx: uniqueIndex('idx_catalog_shares_public_token').on(t.publicToken),
  }),
)

export type CatalogShareRow = typeof catalogShares.$inferSelect
export type NewCatalogShare = typeof catalogShares.$inferInsert
