import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { purchasePaymentTermLifecycle } from "../db/purchasePaymentTerm.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { PaymentTermInUseError, PaymentTermNotFoundError } from "../lib/errors.generated";

export interface DeactivatePurchasePaymentTermInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: DeactivatePurchasePaymentTermInput,
  _ctx: CommandContext,
) {
  const paymentTerm = await db
    .selectFrom("PurchasePaymentTerm")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!paymentTerm) {
    return err(new PaymentTermNotFoundError(input.id));
  }
  const nextStatus = purchasePaymentTermLifecycle.tryTransition(paymentTerm.status, "deactivate");
  if (!nextStatus) {
    return ok({ purchasePaymentTerm: paymentTerm });
  }

  const supplierProfile = await db
    .selectFrom("SupplierProfile")
    .selectAll()
    .where("defaultPurchasePaymentTermId", "=", input.id)
    .executeTakeFirst();
  if (supplierProfile) {
    return err(new PaymentTermInUseError(input.id));
  }

  const deactivated = await db
    .updateTable("PurchasePaymentTerm")
    .set({ status: nextStatus })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchasePaymentTerm: deactivated });
}
