/**
 * white_label_configs — white-label-api (wave-10 leaf 7).
 *
 * One row per tenant (UNIQUE tenant_id). Stores custom domain, brand, and
 * portal configuration for white-label deployments.
 *
 * SSL status enforced by CHECK constraint.
 */
import { pgTable, uuid, text, timestamp, index, check, uniqueIndex } from 'drizzle-orm/pg-core'
import { sql } from 'drizzle-orm'
import { tenants } from './tenants'

export const whiteLabelConfigs = pgTable(
  'white_label_configs',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    tenantId: uuid('tenant_id')
      .notNull()
      .unique()
      .references(() => tenants.id, { onDelete: 'cascade' }),
    // Custom domain (e.g. app.acme.com)
    customDomain: text('custom_domain').unique(),
    // 'pending' | 'active' | 'failed'
    sslStatus: text('ssl_status').notNull().default('pending'),
    brandName: text('brand_name'),
    logoUrl: text('logo_url'),
    primaryColor: text('primary_color'),
    faviconUrl: text('favicon_url'),
    customCss: text('custom_css'),
    apiDomain: text('api_domain'),
    portalDomain: text('portal_domain'),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => ({
    tenantIdx: index('idx_white_label_tenant').on(t.tenantId),
    domainIdx: uniqueIndex('idx_white_label_domain').on(t.customDomain),
    sslStatusCheck: check(
      'white_label_configs_ssl_status_check',
      sql`${t.sslStatus} IN ('pending', 'active', 'failed')`,
    ),
  }),
)

export type WhiteLabelConfigRow = typeof whiteLabelConfigs.$inferSelect
export type NewWhiteLabelConfig = typeof whiteLabelConfigs.$inferInsert
