/**
 * Customer settings query helpers — settings-customers (wave 11).
 *
 * Reads and writes customer-defaults columns from tenant_settings:
 *   - customer_default_currency
 *   - customer_auto_invite_portal
 *   - customer_default_portal_role (read-only, always 'customer_viewer')
 *
 * Also reads default_payment_terms_days which is owned by invoices-core.
 *
 * Routes MUST NOT import raw Drizzle tables — they call these helpers.
 */
import { eq } from 'drizzle-orm'
import type { Db } from '../client'
import { tenantSettings } from '../schema/tenants'
import { auditLog } from './_audit-forward'

// ── Types ─────────────────────────────────────────────────────────────────────

export interface CustomerSettingsDTO {
  default_payment_terms_days: number
  customer_default_currency: string
  customer_auto_invite_portal: 'never' | 'on_creation' | 'on_first_invoice'
  customer_default_portal_role: 'customer_viewer'
}

export interface UpdateCustomerSettingsBody {
  customer_default_currency?: string
  customer_auto_invite_portal?: 'never' | 'on_creation' | 'on_first_invoice'
}

// ── getCustomerSettings ───────────────────────────────────────────────────────

export async function getCustomerSettings(
  db: Db,
  tenantId: string,
): Promise<CustomerSettingsDTO> {
  const [row] = await db
    .select({
      defaultPaymentTermsDays: tenantSettings.defaultPaymentTermsDays,
      customerDefaultCurrency: tenantSettings.customerDefaultCurrency,
      customerAutoInvitePortal: tenantSettings.customerAutoInvitePortal,
      customerDefaultPortalRole: tenantSettings.customerDefaultPortalRole,
    })
    .from(tenantSettings)
    .where(eq(tenantSettings.tenantId, tenantId))
    .limit(1)

  if (!row) {
    return {
      default_payment_terms_days: 30,
      customer_default_currency: 'ILS',
      customer_auto_invite_portal: 'never',
      customer_default_portal_role: 'customer_viewer',
    }
  }

  return {
    default_payment_terms_days: row.defaultPaymentTermsDays,
    customer_default_currency: row.customerDefaultCurrency,
    customer_auto_invite_portal: row.customerAutoInvitePortal as 'never' | 'on_creation' | 'on_first_invoice',
    customer_default_portal_role: 'customer_viewer',
  }
}

// ── updateCustomerSettings ────────────────────────────────────────────────────

export async function updateCustomerSettings(
  db: Db,
  tenantId: string,
  actorId: string,
  patch: UpdateCustomerSettingsBody,
): Promise<CustomerSettingsDTO> {
  await db.transaction(async (tx) => {
    await tx
      .update(tenantSettings)
      .set({
        ...(patch.customer_default_currency !== undefined && { customerDefaultCurrency: patch.customer_default_currency }),
        ...(patch.customer_auto_invite_portal !== undefined && { customerAutoInvitePortal: patch.customer_auto_invite_portal }),
        updatedAt: new Date(),
      })
      .where(eq(tenantSettings.tenantId, tenantId))

    await tx.insert(auditLog).values({
      tenantId,
      actorId,
      actorType: 'user',
      entityType: 'customer_settings',
      entityId: tenantId,
      action: 'update',
      changes: null,
    })
  })

  return getCustomerSettings(db, tenantId)
}

// ── resolveAutoInviteMode ─────────────────────────────────────────────────────

export async function resolveAutoInviteMode(
  db: Db,
  tenantId: string,
): Promise<'never' | 'on_creation' | 'on_first_invoice'> {
  const settings = await getCustomerSettings(db, tenantId)
  return settings.customer_auto_invite_portal
}
