/**
 * POST /v1/invoices/:id/send — zapier-make-integration (wave-13).
 * Marks an approved invoice as sent (issued) and emits invoice.issued webhook.
 *
 * Auth: scope `invoices:write`.
 * Tier: Business+ required.
 */
import { invoices } from '@zync/db'
import { eq, and } from 'drizzle-orm'
import { serializeInvoice, hasScope, errForbiddenScope } from '../index'
import type { PublicApiContext } from '../app'

/** POST /v1/invoices/:id/send */
export async function sendInvoice(ctx: PublicApiContext, id: string): Promise<Response> {
  if (!hasScope(ctx.scopes, 'invoices:write')) return errForbiddenScope('invoices:write')
  const { db, tenantId } = ctx

  const [invoice] = await db
    .select()
    .from(invoices)
    .where(and(eq(invoices.id, id), eq(invoices.tenantId, tenantId)))
    .limit(1)

  if (!invoice) {
    return new Response(JSON.stringify({ error: 'not_found', message: 'Invoice not found' }), {
      status: 404, headers: { 'Content-Type': 'application/json' },
    })
  }

  // Only DRAFT or APPROVED invoices can be sent
  if (!['DRAFT', 'APPROVED', 'PROFORMA_APPROVED'].includes(invoice.status)) {
    return new Response(
      JSON.stringify({ error: 'validation_error', message: `Invoice in status '${invoice.status}' cannot be sent` }),
      { status: 422, headers: { 'Content-Type': 'application/json' } },
    )
  }

  const [updated] = await db
    .update(invoices)
    .set({ status: 'SENT', updatedAt: new Date() })
    .where(and(eq(invoices.id, id), eq(invoices.tenantId, tenantId)))
    .returning()

  if (!updated) {
    return new Response(JSON.stringify({ error: 'internal_error', message: 'Failed to send invoice' }), {
      status: 500, headers: { 'Content-Type': 'application/json' },
    })
  }

  return new Response(
    JSON.stringify(serializeInvoice(
      {
        id: updated.id,
        customerId: updated.customerId,
        projectId: updated.projectId,
        invoiceNumber: updated.invoiceNumber,
        proformaNumber: updated.proformaNumber,
        status: updated.status,
        currency: updated.currency,
        issueDate: updated.issueDate,
        taxIssueDate: updated.taxIssueDate,
        dueDate: updated.dueDate,
        vatRate: updated.vatRate,
        subtotal: updated.subtotal,
        vatAmount: updated.vatAmount,
        total: updated.total,
        notes: updated.notes,
        source: updated.source,
        paidAt: updated.paidAt,
        createdAt: updated.createdAt,
        updatedAt: updated.updatedAt,
      },
      [],
    )),
    { status: 200, headers: { 'Content-Type': 'application/json' } },
  )
}
