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

export interface ActivatePurchasePaymentTermInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: ActivatePurchasePaymentTermInput,
  ctx: CommandContext,
) {
  const paymentTerm = await selectOne(db, "PurchasePaymentTerm", "id", input.id, true);
  if (!paymentTerm) {
    return err(new PaymentTermNotFoundError(input.id));
  }
  if (paymentTerm.status === "ACTIVE") {
    return ok({ purchasePaymentTerm: paymentTerm });
  }

  const validation = validateScheduleLines(
    decodeJson(paymentTerm.scheduleLines, [] as Array<Record<string, unknown>>),
  );
  if (validation) {
    return err(new InvalidTermConfigurationError(input.id));
  }

  const activated = await db
    .updateTable("PurchasePaymentTerm")
    .set({ status: "ACTIVE", updatedAt: new Date() })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchasePaymentTerm: activated });
}
