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

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 updated = await db
    .updateTable("SalesPriceList")
    .set({
      name: input.name ?? salesPriceList.name,
      code: input.code === undefined ? salesPriceList.code : input.code,
      priority: input.priority ?? salesPriceList.priority,
      notes: input.notes === undefined ? salesPriceList.notes : input.notes,
      updatedAt: new Date(),
    })
    .where("id", "=", input.salesPriceListId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesPriceList: updated! });
}
