/**
 * users — global user accounts (one user, many tenant memberships).
 * foundation-auth-rbac. Postgres / Neon via Hyperdrive.
 *
 * Signup creates users with email_verified_at NULL (PENDING_EMAIL).
 * Per-tenant freeze lives on tenant_memberships.status, NOT here.
 */
import { pgTable, uuid, text, boolean, timestamp, index, check, numeric } from 'drizzle-orm/pg-core'
import { sql } from 'drizzle-orm'

export const users = pgTable(
  'users',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    email: text('email').notNull().unique(),
    passwordHash: text('password_hash').notNull(),
    name: text('name'),
    avatarUrl: text('avatar_url'),
    phone: text('phone'),
    emailVerifiedAt: timestamp('email_verified_at', { withTimezone: true }),
    // status: 'active' | 'suspended'
    status: text('status').notNull().default('active'),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    // auth-2fa: phone OTP second factor
    twoFactorEnabled: boolean('two_factor_enabled').notNull().default(false),
    // SHA-256(phone_e164) hex — never raw phone; display-masking only
    twoFactorPhone: text('two_factor_phone'),
    // Last 2 digits of phone for masked display (e.g. "+972 ••••••44")
    twoFactorPhoneSuffix: text('two_factor_phone_suffix'),
    // admin-reports-analytics: last successful login timestamp
    lastLoginAt: timestamp('last_login_at', { withTimezone: true }),
    hourlyCost: numeric('hourly_cost', { precision: 8, scale: 2 }),
    // settings-module: pending email change (opaque token stored hashed)
    pendingEmail: text('pending_email'),
    pendingEmailToken: text('pending_email_token'),
    pendingEmailExpiresAt: timestamp('pending_email_expires_at', { withTimezone: true }),
  },
  (t) => ({
    emailIdx: index('users_email_idx').on(t.email),
    statusCheck: check('users_status_check', sql`${t.status} IN ('active', 'suspended')`),
    lastLoginAtIdx: index('idx_users_last_login').on(t.lastLoginAt),
  }),
)

export type UserRow = typeof users.$inferSelect
export type NewUser = typeof users.$inferInsert
