/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unused-vars */
import type { Transaction } from "../generated/kysely-tailordb";
import { PaymentTermInUseError, PaymentTermNotFoundError } from "../lib/errors.generated";
import { selectOne } from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface DeactivatePurchasePaymentTermInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: DeactivatePurchasePaymentTermInput,
  ctx: CommandContext,
) {
  const paymentTerm = await selectOne(db, "PurchasePaymentTerm", "id", input.id, true);
  if (!paymentTerm) {
    return err(new PaymentTermNotFoundError(input.id));
  }
  if (paymentTerm.status === "INACTIVE") {
    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: "INACTIVE", updatedAt: new Date() })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchasePaymentTerm: deactivated });
}
