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

export interface DeactivateSalesPaymentTermInput {
  salesPaymentTermId: string;
}

export async function run(
  db: Transaction,
  input: DeactivateSalesPaymentTermInput,
  ctx: CommandContext,
) {
  void ctx;
  const salesPaymentTerm = await db
    .selectFrom("SalesPaymentTerm")
    .selectAll()
    .where("id", "=", input.salesPaymentTermId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesPaymentTerm) {
    return err(new SalespaymenttermNotFoundError(input.salesPaymentTermId));
  }
  if (salesPaymentTerm.status !== "ACTIVE") {
    return err(new InvalidSalespaymenttermStatusError(input.salesPaymentTermId));
  }
  const updated = await db
    .updateTable("SalesPaymentTerm")
    .set({ status: "INACTIVE", updatedAt: new Date() })
    .where("id", "=", input.salesPaymentTermId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesPaymentTerm: updated! });
}
