/* 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 {
  ImmutableOwnerChangeError,
  InvalidListPriorityError,
  PriceListNotFoundError,
} from "../lib/errors.generated";
import { selectOne } from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export type UpdatePurchasePriceListInput = {
  id: string;
  companyId?: string;
  supplierId?: string;
  name?: string;
  code?: string;
  priority?: number;
  notes?: string | null;
};
export async function run(
  db: Transaction,
  input: UpdatePurchasePriceListInput,
  ctx: CommandContext,
) {
  const existing = await selectOne(db, "PurchasePriceList", "id", input.id, true);
  if (!existing) {
    return err(new PriceListNotFoundError(input.id));
  }

  if (
    (input.companyId && input.companyId !== existing.companyId) ||
    (input.supplierId && input.supplierId !== existing.supplierId)
  ) {
    return err(new ImmutableOwnerChangeError(input.id));
  }
  if (input.priority !== undefined && input.priority < 0) {
    return err(new InvalidListPriorityError(String(input.priority)));
  }

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

  return ok({ purchasePriceList });
}
