/**
 * user_preferences — foundation-auth-rbac.
 * Per-(user, tenant) preferences persisted across sessions.
 * `notification_channels` is authoritative for per-user delivery prefs,
 * read by NotificationAdapter.canDeliver() downstream.
 */
import { pgTable, uuid, text, boolean, jsonb, timestamp, primaryKey, check } from 'drizzle-orm/pg-core'
import { sql } from 'drizzle-orm'
import { users } from './users'
import { tenants } from './tenants'

export const userPreferences = pgTable(
  'user_preferences',
  {
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    tenantId: uuid('tenant_id')
      .notNull()
      .references(() => tenants.id, { onDelete: 'cascade' }),
    notificationChannels: jsonb('notification_channels')
      .notNull()
      .default(sql`'{"email":[],"telegram":[]}'::jsonb`),
    sidebarCollapsed: boolean('sidebar_collapsed').notNull().default(false),
    defaultCurrency: text('default_currency'), // NULL = use tenant default
    // IANA; concrete display zone (no tenant inheritance — see timezone-handling)
    timezone: text('timezone').notNull().default('Asia/Jerusalem'),
    locale: text('locale'), // 'he' | 'en'; NULL = tenant default
    // DEFERRED FK -> projects(id) ON DELETE SET NULL.
    // The `projects` table is built in wave 3 (projects-module); that module
    // owns the `ALTER TABLE user_preferences ADD CONSTRAINT ... FOREIGN KEY`.
    // Intentionally NO .references() here — would fail (table not yet created).
    defaultTimerProjectId: uuid('default_timer_project_id'),
    dashboardWidgets: jsonb('dashboard_widgets').notNull().default(sql`'[]'::jsonb`),
    uiTheme: text('ui_theme').default('dark'),
    uiShell: text('ui_shell').notNull().default('os'),
    // session-security (wave-13): email notification on new login
    notifyNewLogin: boolean('notify_new_login').notNull().default(true),
    updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow(),
  },
  (t) => ({
    pk: primaryKey({ columns: [t.userId, t.tenantId] }),
    uiThemeCheck: check('user_preferences_ui_theme_check', sql`ui_theme IN ('dark','light','system')`),
    uiShellCheck: check('user_preferences_ui_shell_check', sql`ui_shell IN ('classic','os')`),
  }),
)

export type UserPreferencesRow = typeof userPreferences.$inferSelect
export type NewUserPreferences = typeof userPreferences.$inferInsert
