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

export interface ActivateSalesPriceListInput {
  salesPriceListId: string;
}

export async function run(
  db: Transaction,
  input: ActivateSalesPriceListInput,
  ctx: CommandContext,
  organizationQueries: Pick<OrganizationQueries, "getCompany">,
) {
  const salesPriceList = await db
    .selectFrom("SalesPriceList")
    .selectAll()
    .where("id", "=", input.salesPriceListId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesPriceList) {
    return err(new SalespricelistNotFoundError(input.salesPriceListId));
  }
  const nextStatus = salesPriceListLifecycle.tryTransition(salesPriceList.status, "activate");
  if (!nextStatus) {
    return err(new InvalidSalespricelistStatusError(input.salesPriceListId));
  }
  const { company } = (
    await organizationQueries.getCompany(db, { id: salesPriceList.companyId }, ctx)
  ).value;
  if (!company) {
    return err(new CompanyNotFoundError(salesPriceList.companyId));
  }
  const updated = await db
    .updateTable("SalesPriceList")
    .set({ status: nextStatus })
    .where("id", "=", input.salesPriceListId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ salesPriceList: updated });
}
