/**
 * Invoice payment link query helpers — invoice-payment-link-generation (wave-12).
 *
 * Thin write helpers used by the payment-link send route.
 * Route files MUST NOT import raw Drizzle tables — they call these helpers.
 */
import { and, eq } from 'drizzle-orm'
import type { Db } from '../client'
import { invoices } from '../schema/invoices'
import { tenantEmailTemplates } from '../schema/tenant-email-templates'

// ── stampPaymentLinkSentAt ────────────────────────────────────────────────────

/**
 * Set `invoices.payment_link_sent_at` to now() for a given invoice (tenant-scoped).
 */
export async function stampPaymentLinkSentAt(
  db: Db,
  tenantId: string,
  invoiceId: string,
): Promise<void> {
  await db
    .update(invoices)
    .set({ paymentLinkSentAt: new Date() })
    .where(and(eq(invoices.id, invoiceId), eq(invoices.tenantId, tenantId)))
}

// ── getPaymentLinkEmailTemplate ──────────────────────────────────────────────

/**
 * Load the `payment_link` email template for a tenant, if configured and active.
 * Returns null if no custom template exists.
 */
export async function getPaymentLinkEmailTemplate(
  db: Db,
  tenantId: string,
): Promise<{ subject: string; bodyText: string } | null> {
  const rows = await db
    .select({
      subject: tenantEmailTemplates.subject,
      bodyText: tenantEmailTemplates.bodyText,
    })
    .from(tenantEmailTemplates)
    .where(
      and(
        eq(tenantEmailTemplates.tenantId, tenantId),
        eq(tenantEmailTemplates.templateKey, 'payment_link'),
        eq(tenantEmailTemplates.isActive, true),
      ),
    )
    .limit(1)

  if (!rows[0]) return null
  return { subject: rows[0].subject, bodyText: rows[0].bodyText }
}
