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

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));
  }
  if (!["DRAFT", "ISSUED"].includes(salesInvoice.status)) {
    return err(new InvalidInvoiceStatusError(input.salesInvoiceId));
  }
  if (salesInvoice.arHandoffAccepted) {
    return err(new InvoiceCancellationBlockedError(input.salesInvoiceId));
  }
  const updated = await db
    .updateTable("SalesInvoice")
    .set({ status: "CANCELLED", updatedAt: new Date() })
    .where("id", "=", input.salesInvoiceId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesInvoice: updated! });
}
