import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { salesPriceRuleLifecycle } from "../db/salesPriceRule.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  InvalidEffectiveRangeError,
  InvalidSalespriceruleStatusError,
  InvalidUnitPriceError,
  PriceListNotFoundError,
  SalespriceruleNotFoundError,
} from "../lib/errors.generated";

export interface ActivateSalesPriceRuleInput {
  salesPriceRuleId: string;
}

export async function run(
  db: Transaction,
  input: ActivateSalesPriceRuleInput,
  ctx: CommandContext,
) {
  void ctx;
  const salesPriceRule = await db
    .selectFrom("SalesPriceRule")
    .selectAll()
    .where("id", "=", input.salesPriceRuleId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesPriceRule) {
    return err(new SalespriceruleNotFoundError(input.salesPriceRuleId));
  }
  const nextStatus = salesPriceRuleLifecycle.tryTransition(salesPriceRule.status, "activate");
  if (!nextStatus) {
    return err(new InvalidSalespriceruleStatusError(input.salesPriceRuleId));
  }
  const salesPriceList = await db
    .selectFrom("SalesPriceList")
    .selectAll()
    .where("id", "=", salesPriceRule.salesPriceListId)
    .executeTakeFirst();
  if (!salesPriceList) {
    return err(new PriceListNotFoundError(salesPriceRule.salesPriceListId));
  }
  if (salesPriceRule.unitPrice <= 0 || salesPriceRule.minimumQuantity < 0) {
    return err(new InvalidUnitPriceError(input.salesPriceRuleId));
  }
  if (
    salesPriceRule.effectiveFrom &&
    salesPriceRule.effectiveTo &&
    salesPriceRule.effectiveTo < salesPriceRule.effectiveFrom
  ) {
    return err(new InvalidEffectiveRangeError(input.salesPriceRuleId));
  }
  const updated = await db
    .updateTable("SalesPriceRule")
    .set({ status: nextStatus })
    .where("id", "=", input.salesPriceRuleId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ salesPriceRule: updated });
}
