import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { Transaction } from "../generated/kysely-tailordb";
import { encodeJson, type SalesInvoiceLineInput } from "../lib/domain";
import {
  CrossCompanyReferenceError,
  InvalidInvoiceLineError,
  SalesOrderNotFoundError,
} from "../lib/errors.generated";

export interface SalesInvoiceHeaderInput {
  companyId: string;
  salesOrderId: string;
  shipmentId?: string | null;
  invoiceDate?: Date;
  notes?: string;
}

export interface CreateSalesInvoiceInput {
  header: SalesInvoiceHeaderInput;
  lines: SalesInvoiceLineInput[];
}

export async function run<CF extends Record<string, unknown>, LCF extends Record<string, unknown>>(
  db: Transaction,
  input: {
    header: SalesInvoiceHeaderInput & CF;
    lines: (SalesInvoiceLineInput & LCF)[];
  },
  ctx: CommandContext,
) {
  void ctx;
  const { header, lines } = input;
  const salesOrder = await db
    .selectFrom("SalesOrder")
    .selectAll()
    .where("id", "=", header.salesOrderId)
    .executeTakeFirst();
  if (!salesOrder) {
    return err(new SalesOrderNotFoundError(header.salesOrderId));
  }
  if (salesOrder.companyId !== header.companyId) {
    return err(new CrossCompanyReferenceError(header.salesOrderId));
  }
  if (!lines.length) {
    return err(new InvalidInvoiceLineError(header.salesOrderId));
  }
  for (const line of lines) {
    const orderLine = await db
      .selectFrom("SalesOrderLine")
      .selectAll()
      .where("id", "=", line.salesOrderLineId)
      .executeTakeFirst();
    if (orderLine?.salesOrderId !== header.salesOrderId || line.quantity <= 0) {
      return err(new InvalidInvoiceLineError(line.salesOrderLineId));
    }
  }
  const salesInvoice = await db
    .insertInto("SalesInvoice")
    .values({
      // Header input first (incl. custom fields) so command-set columns always win.
      ...(header as Record<string, unknown>),
      companyId: header.companyId,
      customerId: salesOrder.customerId,
      salesOrderId: header.salesOrderId,
      paymentTermId: salesOrder.paymentTermId,
      shipmentId: header.shipmentId ?? null,
      status: "DRAFT",
      invoiceNumber: null,
      invoiceDate: header.invoiceDate ?? new Date(),
      billingPolicy: null,
      paymentTermSnapshot: salesOrder.paymentTermSnapshot,
      dueSchedule: null,
      taxIdentitySnapshot: null,
      deliveryMetadata: null,
      arHandoffAccepted: false,
      notes: header.notes ?? null,
    })
    .returningAll()
    .executeTakeFirstOrThrow();
  for (const line of lines) {
    const {
      salesOrderLineId,
      shipmentLineId,
      quantity,
      unitPrice,
      taxCode,
      taxableAmount,
      taxAmount,
      billingPolicy,
      ...lineCustomFields
    } = line;
    const orderLine = await db
      .selectFrom("SalesOrderLine")
      .selectAll()
      .where("id", "=", salesOrderLineId)
      .executeTakeFirst();
    if (!orderLine) {
      return err(new InvalidInvoiceLineError(salesOrderLineId));
    }
    await db
      .insertInto("SalesInvoiceLine")
      .values({
        // Custom fields first so command-set columns always win.
        ...(lineCustomFields as Record<string, unknown>),
        salesInvoiceId: salesInvoice.id,
        salesOrderLineId,
        shipmentLineId: shipmentLineId ?? null,
        quantity,
        unitPrice: unitPrice ?? orderLine.unitPrice,
        taxCode: taxCode ?? null,
        taxableAmount: taxableAmount ?? null,
        taxAmount: taxAmount ?? null,
        billingPolicy: billingPolicy ?? (shipmentLineId ? "SHIPMENT" : orderLine.billingPolicy),
        orderPriceSnapshot: encodeJson({ unitPrice: orderLine.unitPrice }),
      })
      .executeTakeFirst();
  }
  return ok({ salesInvoice });
}
