/**
 * Timezone query helpers — timezone-handling (wave-11 leaf-E).
 */
import { eq } from 'drizzle-orm'
import type { Db } from '../client'
import { userPreferences } from '../schema/user-preferences'
import { tenants } from '../schema/tenants'
import { auditLog } from './_audit-forward'

export async function getTenantTimezone(db: Db, tenantId: string): Promise<string> {
  const [row] = await db
    .select({ timezone: tenants.defaultTimezone })
    .from(tenants)
    .where(eq(tenants.id, tenantId))
    .limit(1)

  return row?.timezone ?? 'Asia/Jerusalem'
}

// ── setUserTimezone ────────────────────────────────────────────────────────────

/**
 * Upserts the timezone for a user within a tenant.
 * Creates the preferences row if it doesn't exist.
 */
export async function setUserTimezone(
  db: Db,
  userId: string,
  tenantId: string,
  timezone: string,
): Promise<void> {
  await db
    .insert(userPreferences)
    .values({ userId, tenantId, timezone })
    .onConflictDoUpdate({
      target: [userPreferences.userId, userPreferences.tenantId],
      set: { timezone, updatedAt: new Date() },
    })
}

// ── setTenantTimezone ──────────────────────────────────────────────────────────

export async function setTenantTimezone(
  db: Db,
  tenantId: string,
  actorId: string,
  timezone: string,
): Promise<{ defaultTimezone: string }> {
  await db
    .update(tenants)
    .set({ defaultTimezone: timezone })
    .where(eq(tenants.id, tenantId))

  await db.insert(auditLog).values({
    tenantId,
    actorId,
    actorType: 'user',
    entityType: 'tenant',
    entityId: tenantId,
    action: 'update_timezone',
    changes: null,
  })

  return { defaultTimezone: timezone }
}
