import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { salesPaymentTermLifecycle } from "../db/salesPaymentTerm.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  decodeJson,
  validateScheduleLines,
  type PaymentTermScheduleLineInput,
} from "../lib/domain";
import {
  InvalidPaymentScheduleError,
  InvalidSalespaymenttermStatusError,
  SalespaymenttermNotFoundError,
} from "../lib/errors.generated";

export interface ActivateSalesPaymentTermInput {
  salesPaymentTermId: string;
}

export async function run(
  db: Transaction,
  input: ActivateSalesPaymentTermInput,
  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));
  }
  const nextStatus = salesPaymentTermLifecycle.tryTransition(salesPaymentTerm.status, "activate");
  if (!nextStatus) {
    return err(new InvalidSalespaymenttermStatusError(input.salesPaymentTermId));
  }
  if (
    validateScheduleLines(
      decodeJson<PaymentTermScheduleLineInput[]>(salesPaymentTerm.scheduleLines, []),
    )
  ) {
    return err(new InvalidPaymentScheduleError(input.salesPaymentTermId));
  }
  const updated = await db
    .updateTable("SalesPaymentTerm")
    .set({ status: nextStatus })
    .where("id", "=", input.salesPaymentTermId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ salesPaymentTerm: updated });
}
