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<CF extends Record<string, unknown>>(
  db: Transaction,
  input: UpdateSalesPaymentTermInput & Partial<CF>,
  ctx: CommandContext,
) {
  void ctx;
  const { salesPaymentTermId, name, code, scheduleLines, notes, ...customFields } = input;
  const salesPaymentTerm = await db
    .selectFrom("SalesPaymentTerm")
    .selectAll()
    .where("id", "=", salesPaymentTermId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesPaymentTerm) {
    return err(new SalespaymenttermNotFoundError(salesPaymentTermId));
  }
  if (!["DRAFT", "ACTIVE"].includes(salesPaymentTerm.status)) {
    return err(new SalespaymenttermNotEditableError(salesPaymentTermId));
  }
  if (scheduleLines && validateScheduleLines(scheduleLines)) {
    return err(new InvalidPaymentScheduleError(salesPaymentTermId));
  }
  const updates: Updateable<"SalesPaymentTerm"> = {
    ...(customFields as Updateable<"SalesPaymentTerm">),
  };
  if (name !== undefined) updates.name = name;
  if (code !== undefined) updates.code = code;
  if (scheduleLines !== undefined) updates.scheduleLines = encodeJson(scheduleLines);
  if (notes !== undefined) updates.notes = notes;

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

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