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

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));
  }
  if (salesPaymentTerm.status !== "DRAFT") {
    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: "ACTIVE", updatedAt: new Date() })
    .where("id", "=", input.salesPaymentTermId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesPaymentTerm: updated! });
}
