/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unused-vars */
import type { Transaction } from "../generated/kysely-tailordb";
import {
  EmptyScheduleError,
  ImmutableCompanyScopeError,
  InvalidDiscountConfigurationError,
  InvalidInstallmentTotalError,
  InvalidScheduleLineError,
  PaymentTermNotFoundError,
} from "../lib/errors.generated";
import {
  decodeJson,
  encodeJson,
  selectOne,
  validateScheduleLines,
  type PaymentTermScheduleLineInput,
} from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export type UpdatePurchasePaymentTermInput = {
  id: string;
  companyId?: string;
  name?: string;
  code?: string;
  scheduleLines?: PaymentTermScheduleLineInput[];
  notes?: string | null;
};
export async function run(
  db: Transaction,
  input: UpdatePurchasePaymentTermInput,
  ctx: CommandContext,
) {
  const existing = await selectOne(db, "PurchasePaymentTerm", "id", input.id, true);
  if (!existing) {
    return err(new PaymentTermNotFoundError(input.id));
  }

  if (input.companyId && input.companyId !== existing.companyId) {
    return err(new ImmutableCompanyScopeError(input.id));
  }

  const scheduleLines =
    input.scheduleLines ?? decodeJson<PaymentTermScheduleLineInput[]>(existing.scheduleLines, []);
  const validation = validateScheduleLines(scheduleLines);
  if (validation === "EMPTY_SCHEDULE") {
    return err(new EmptyScheduleError(input.id));
  }
  if (validation === "INVALID_INSTALLMENT_TOTAL") {
    return err(new InvalidInstallmentTotalError(input.id));
  }
  if (validation === "INVALID_SCHEDULE_LINE") {
    return err(new InvalidScheduleLineError(input.id));
  }
  if (validation === "INVALID_DISCOUNT_CONFIGURATION") {
    return err(new InvalidDiscountConfigurationError(input.id));
  }

  const paymentTerm = await db
    .updateTable("PurchasePaymentTerm")
    .set({
      name: input.name ?? existing.name,
      code: input.code ?? existing.code,
      scheduleLines: encodeJson(scheduleLines),
      notes: input.notes === undefined ? existing.notes : input.notes,
      updatedAt: new Date(),
    })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchasePaymentTerm: paymentTerm });
}
