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

export type UpdateSalesPaymentTermInput = {
  salesPaymentTermId: string;
  name?: string;
  code?: string | null;
  scheduleLines?: PaymentTermScheduleLineInput[];
  notes?: string | null;
};
export async function run(
  db: Transaction,
  input: UpdateSalesPaymentTermInput,
  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 (!["DRAFT", "ACTIVE"].includes(salesPaymentTerm.status)) {
    return err(new SalespaymenttermNotEditableError(input.salesPaymentTermId));
  }
  if (input.scheduleLines && validateScheduleLines(input.scheduleLines)) {
    return err(new InvalidPaymentScheduleError(input.salesPaymentTermId));
  }
  const updated = await db
    .updateTable("SalesPaymentTerm")
    .set({
      name: input.name ?? salesPaymentTerm.name,
      code: input.code === undefined ? salesPaymentTerm.code : input.code,
      scheduleLines:
        input.scheduleLines === undefined
          ? salesPaymentTerm.scheduleLines
          : encodeJson(input.scheduleLines),
      notes: input.notes === undefined ? salesPaymentTerm.notes : input.notes,
      updatedAt: new Date(),
    })
    .where("id", "=", input.salesPaymentTermId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesPaymentTerm: updated! });
}
