/**
 * Invoice PDF template query helpers — invoice-pdf-customization (wave-11).
 *
 * Reads/writes the five invoice_pdf_* columns on tenant_settings.
 * Does NOT use getTenantSettings/upsertTenantSettings from the AI package.
 */
import { eq } from 'drizzle-orm'
import { z } from 'zod'
import type { Db } from '../client'
import { tenantSettings } from '../schema/tenants'

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

export type InvoicePdfLayout = 'classic' | 'modern' | 'minimal'
export type InvoicePdfDateFormat = 'dd.MM.yyyy' | 'yyyy-MM-dd' | 'MMMM d, yyyy'

export interface InvoicePdfTemplate {
  layout: InvoicePdfLayout
  showProject: boolean
  showSku: boolean
  dateFormat: InvoicePdfDateFormat
  accentHex: string | null
}

export type UpdateInvoicePdfTemplate = Partial<InvoicePdfTemplate>

export const INVOICE_PDF_TEMPLATE_DEFAULTS: InvoicePdfTemplate = {
  layout: 'classic',
  showProject: false,
  showSku: false,
  dateFormat: 'dd.MM.yyyy',
  accentHex: null,
}

// ── Zod schemas ───────────────────────────────────────────────────────────────

export const invoicePdfTemplateSchema = z.object({
  layout: z.enum(['classic', 'modern', 'minimal']).optional(),
  showProject: z.boolean().optional(),
  showSku: z.boolean().optional(),
  dateFormat: z.enum(['dd.MM.yyyy', 'yyyy-MM-dd', 'MMMM d, yyyy']).optional(),
  accentHex: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(),
})

export type InvoicePdfTemplatePatch = z.infer<typeof invoicePdfTemplateSchema>

// ── Helpers ───────────────────────────────────────────────────────────────────

function mapRow(row: {
  invoicePdfLayout: string
  invoicePdfShowProject: boolean
  invoicePdfShowSku: boolean
  invoicePdfDateFormat: string
  invoicePdfAccentHex: string | null
}): InvoicePdfTemplate {
  return {
    layout: row.invoicePdfLayout as InvoicePdfLayout,
    showProject: row.invoicePdfShowProject,
    showSku: row.invoicePdfShowSku,
    dateFormat: row.invoicePdfDateFormat as InvoicePdfDateFormat,
    accentHex: row.invoicePdfAccentHex ?? null,
  }
}

// ── Query helpers ─────────────────────────────────────────────────────────────

/**
 * Get the current PDF template settings for a tenant.
 * Returns INVOICE_PDF_TEMPLATE_DEFAULTS if no row exists.
 */
export async function getInvoicePdfTemplate(
  db: Db,
  tenantId: string,
): Promise<InvoicePdfTemplate> {
  const [row] = await db
    .select({
      invoicePdfLayout: tenantSettings.invoicePdfLayout,
      invoicePdfShowProject: tenantSettings.invoicePdfShowProject,
      invoicePdfShowSku: tenantSettings.invoicePdfShowSku,
      invoicePdfDateFormat: tenantSettings.invoicePdfDateFormat,
      invoicePdfAccentHex: tenantSettings.invoicePdfAccentHex,
    })
    .from(tenantSettings)
    .where(eq(tenantSettings.tenantId, tenantId))
    .limit(1)

  if (!row) return { ...INVOICE_PDF_TEMPLATE_DEFAULTS }

  return mapRow(row)
}

/**
 * Upsert PDF template settings for a tenant.
 * Normalizes accentHex to lowercase for stable comparison.
 * Returns the updated merged template.
 */
export async function updateInvoicePdfTemplate(
  db: Db,
  tenantId: string,
  patch: InvoicePdfTemplatePatch,
): Promise<InvoicePdfTemplate> {
  const normalizedPatch = {
    ...(patch.layout !== undefined && { invoicePdfLayout: patch.layout }),
    ...(patch.showProject !== undefined && { invoicePdfShowProject: patch.showProject }),
    ...(patch.showSku !== undefined && { invoicePdfShowSku: patch.showSku }),
    ...(patch.dateFormat !== undefined && { invoicePdfDateFormat: patch.dateFormat }),
    ...(patch.accentHex !== undefined && {
      invoicePdfAccentHex: patch.accentHex ? patch.accentHex.toLowerCase() : null,
    }),
    updatedAt: new Date(),
  }

  const [row] = await db
    .insert(tenantSettings)
    .values({
      tenantId,
      invoicePdfLayout: patch.layout ?? INVOICE_PDF_TEMPLATE_DEFAULTS.layout,
      invoicePdfShowProject: patch.showProject ?? INVOICE_PDF_TEMPLATE_DEFAULTS.showProject,
      invoicePdfShowSku: patch.showSku ?? INVOICE_PDF_TEMPLATE_DEFAULTS.showSku,
      invoicePdfDateFormat: patch.dateFormat ?? INVOICE_PDF_TEMPLATE_DEFAULTS.dateFormat,
      invoicePdfAccentHex: patch.accentHex
        ? patch.accentHex.toLowerCase()
        : INVOICE_PDF_TEMPLATE_DEFAULTS.accentHex,
    })
    .onConflictDoUpdate({
      target: tenantSettings.tenantId,
      set: normalizedPatch,
    })
    .returning({
      invoicePdfLayout: tenantSettings.invoicePdfLayout,
      invoicePdfShowProject: tenantSettings.invoicePdfShowProject,
      invoicePdfShowSku: tenantSettings.invoicePdfShowSku,
      invoicePdfDateFormat: tenantSettings.invoicePdfDateFormat,
      invoicePdfAccentHex: tenantSettings.invoicePdfAccentHex,
    })

  return mapRow(row!)
}
