import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { Transaction, Updateable } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  SalespricelistNotEditableError,
  SalespricelistNotFoundError,
} from "../lib/errors.generated";

export type UpdateSalesPriceListInput = {
  salesPriceListId: string;
  name?: string;
  code?: string | null;
  priority?: number;
  notes?: string | null;
};
export async function run(db: Transaction, input: UpdateSalesPriceListInput, ctx: CommandContext) {
  void ctx;
  const salesPriceList = await db
    .selectFrom("SalesPriceList")
    .selectAll()
    .where("id", "=", input.salesPriceListId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesPriceList) {
    return err(new SalespricelistNotFoundError(input.salesPriceListId));
  }
  if (!["DRAFT", "ACTIVE"].includes(salesPriceList.status)) {
    return err(new SalespricelistNotEditableError(input.salesPriceListId));
  }
  const company = await db
    .selectFrom("Company")
    .selectAll()
    .where("id", "=", salesPriceList.companyId)
    .executeTakeFirst();
  if (!company) {
    return err(new CompanyNotFoundError(salesPriceList.companyId));
  }
  const updates: Updateable<"SalesPriceList"> = {};
  if (input.name !== undefined) updates.name = input.name;
  if (input.code !== undefined) updates.code = input.code;
  if (input.priority !== undefined) updates.priority = input.priority;
  if (input.notes !== undefined) updates.notes = input.notes;

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

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