import type { Transaction } from "../generated/kysely-tailordb";
import type { defineModule as defineItemManagementModule } from "../../item-management";
type ItemManagementModule = ReturnType<typeof defineItemManagementModule>;
type ItemManagementQueries = ItemManagementModule["queries"];
import {
  CurrencyNotFoundError,
  DuplicateRulePrecedenceError,
  InvalidRuleConfigurationError,
  ItemNotActiveError,
  ItemNotFoundError,
  PriceRuleNotFoundError,
  UnitNotFoundError,
} from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";

export interface ActivatePurchasePriceRuleInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: ActivatePurchasePriceRuleInput,
  ctx: CommandContext,
  itemManagementQueries: Pick<ItemManagementQueries, "getItem">,
) {
  const purchasePriceRule = await db
    .selectFrom("PurchasePriceRule")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!purchasePriceRule) {
    return err(new PriceRuleNotFoundError(input.id));
  }
  if (purchasePriceRule.status === "ACTIVE") {
    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));
  }
  if (
    !(await db.selectFrom("Currency").selectAll().where("id", "=", currencyId).executeTakeFirst())
  ) {
    return err(new CurrencyNotFoundError(currencyId));
  }
  if (!(await db.selectFrom("Unit").selectAll().where("id", "=", unitId).executeTakeFirst())) {
    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: "ACTIVE", updatedAt: new Date() })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchasePriceRule: activated });
}
