import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { purchasePriceRuleLifecycle } from "../db/purchasePriceRule.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CurrencyNotFoundError,
  DuplicateRulePrecedenceError,
  InvalidRuleConfigurationError,
  ItemNotActiveError,
  ItemNotFoundError,
  PriceRuleNotFoundError,
  UnitNotFoundError,
} from "../lib/errors.generated";
import type { ItemManagementQueries, PrimitivesQueries } from "../module";

export interface ActivatePurchasePriceRuleInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: ActivatePurchasePriceRuleInput,
  ctx: CommandContext,
  itemManagementQueries: Pick<ItemManagementQueries, "getItem">,
  primitivesQueries: Pick<PrimitivesQueries, "getCurrency" | "getUnit">,
) {
  const purchasePriceRule = await db
    .selectFrom("PurchasePriceRule")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!purchasePriceRule) {
    return err(new PriceRuleNotFoundError(input.id));
  }
  const nextStatus = purchasePriceRuleLifecycle.tryTransition(purchasePriceRule.status, "activate");
  if (!nextStatus) {
    return ok({ purchasePriceRule });
  }

  const itemId = purchasePriceRule.itemId;
  const currencyId = purchasePriceRule.currencyId;
  const unitId = purchasePriceRule.unitId;
  const { item } = (await itemManagementQueries.getItem(db, { id: itemId }, ctx)).value;
  if (!item) {
    return err(new ItemNotFoundError(itemId));
  }
  if (item.status !== "ACTIVE") {
    return err(new ItemNotActiveError(itemId));
  }
  const { currency } = (await primitivesQueries.getCurrency(db, { id: currencyId }, ctx)).value;
  if (!currency) {
    return err(new CurrencyNotFoundError(currencyId));
  }
  const { unit } = (await primitivesQueries.getUnit(db, { id: unitId }, ctx)).value;
  if (!unit) {
    return err(new UnitNotFoundError(unitId));
  }

  if (
    purchasePriceRule.effectiveTo &&
    purchasePriceRule.effectiveTo < purchasePriceRule.effectiveFrom
  ) {
    return err(new InvalidRuleConfigurationError(input.id));
  }

  const conflictingRule = await db
    .selectFrom("PurchasePriceRule")
    .selectAll()
    .where("itemId", "=", itemId)
    .where("currencyId", "=", currencyId)
    .where("unitId", "=", unitId)
    .where("minimumQuantity", "=", purchasePriceRule.minimumQuantity)
    .where("effectiveFrom", "=", purchasePriceRule.effectiveFrom)
    .where("status", "=", "ACTIVE")
    .executeTakeFirst();
  if (conflictingRule && conflictingRule.id !== input.id) {
    return err(new DuplicateRulePrecedenceError(input.id));
  }

  const activated = await db
    .updateTable("PurchasePriceRule")
    .set({ status: nextStatus })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchasePriceRule: activated });
}
