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";
import type { OrganizationQueries } from "../module";

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

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

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