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

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 updates: Updateable<"SalesPaymentTerm"> = {};
  if (input.name !== undefined) updates.name = input.name;
  if (input.code !== undefined) updates.code = input.code;
  if (input.scheduleLines !== undefined) updates.scheduleLines = encodeJson(input.scheduleLines);
  if (input.notes !== undefined) updates.notes = input.notes;

  if (Object.keys(updates).length === 0) {
    return ok({ salesPaymentTerm });
  }

  const updated = await db
    .updateTable("SalesPaymentTerm")
    .set(updates)
    .where("id", "=", input.salesPaymentTermId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ salesPaymentTerm: updated });
}
