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

export interface ActivateSalesPriceListInput {
  salesPriceListId: string;
}

export async function run(
  db: Transaction,
  input: ActivateSalesPriceListInput,
  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 (salesPriceList.status !== "DRAFT") {
    return err(new InvalidSalespricelistStatusError(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({ status: "ACTIVE", updatedAt: new Date() })
    .where("id", "=", input.salesPriceListId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesPriceList: updated! });
}
