import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { salesInvoiceLifecycle } from "../db/salesInvoice.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  InvalidInvoiceStatusError,
  InvoiceCancellationBlockedError,
  SalesInvoiceNotFoundError,
} from "../lib/errors.generated";

export interface CancelSalesInvoiceInput {
  salesInvoiceId: string;
}

export async function run(db: Transaction, input: CancelSalesInvoiceInput, ctx: CommandContext) {
  void ctx;
  const salesInvoice = await db
    .selectFrom("SalesInvoice")
    .selectAll()
    .where("id", "=", input.salesInvoiceId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesInvoice) {
    return err(new SalesInvoiceNotFoundError(input.salesInvoiceId));
  }
  const nextStatus = salesInvoiceLifecycle.tryTransition(salesInvoice.status, "cancel");
  if (!nextStatus) {
    return err(new InvalidInvoiceStatusError(input.salesInvoiceId));
  }
  if (salesInvoice.arHandoffAccepted) {
    return err(new InvoiceCancellationBlockedError(input.salesInvoiceId));
  }
  const updated = await db
    .updateTable("SalesInvoice")
    .set({ status: nextStatus })
    .where("id", "=", input.salesInvoiceId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ salesInvoice: updated });
}
