/**
 * tenant_modules — per-tenant module enable/disable state.
 * module-management spec. Neon Postgres via Hyperdrive.
 *
 * Composite PK (tenant_id, module_id). The `system` module is NEVER stored
 * here — application logic treats it as always-on by convention.
 */
import {
  pgTable,
  uuid,
  text,
  boolean,
  timestamp,
  index,
  primaryKey,
  check,
} from 'drizzle-orm/pg-core'
import { sql } from 'drizzle-orm'
import { tenants } from './tenants'
import { users } from './users'

export const tenantModules = pgTable(
  'tenant_modules',
  {
    tenantId: uuid('tenant_id')
      .notNull()
      .references(() => tenants.id, { onDelete: 'cascade' }),
    moduleId: text('module_id').notNull(),
    enabled: boolean('enabled').notNull().default(true),
    /** Last time this module was enabled */
    enabledAt: timestamp('enabled_at', { withTimezone: true }),
    /** Last time this module was disabled */
    disabledAt: timestamp('disabled_at', { withTimezone: true }),
    /** User who last toggled it off */
    disabledBy: uuid('disabled_by').references(() => users.id, { onDelete: 'set null' }),
    /** true = system admin forced state; tenant cannot toggle */
    overrideBySystemAdmin: boolean('override_by_system_admin').notNull().default(false),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => ({
    pk: primaryKey({ columns: [t.tenantId, t.moduleId] }),
    tenantIdx: index('idx_tenant_modules_tenant_id').on(t.tenantId),
    moduleIdValid: check(
      'module_id_valid',
      sql`${t.moduleId} IN (
        'system','crm','customers','time_management','projects','tasks',
        'invoices','expenses','billing','calendar','marketing','reports',
        'kb','contractor_payouts','ai_assistant'
      )`,
    ),
  }),
)

export type TenantModuleRow = typeof tenantModules.$inferSelect
export type NewTenantModuleRow = typeof tenantModules.$inferInsert
