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 { validateScheduleLines } from "../lib/domain";
import { InvalidTermConfigurationError, PaymentTermNotFoundError } from "../lib/errors.generated";

export interface ActivatePurchasePaymentTermInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: ActivatePurchasePaymentTermInput,
  _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, "activate");
  if (!nextStatus) {
    return ok({ purchasePaymentTerm: paymentTerm });
  }

  const existingLines = await db
    .selectFrom("PurchasePaymentTermLine")
    .selectAll()
    .where("purchasePaymentTermId", "=", input.id)
    .execute();
  const validation = validateScheduleLines(existingLines);
  if (validation) {
    return err(new InvalidTermConfigurationError(input.id));
  }

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

  return ok({ purchasePaymentTerm: activated });
}
