/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unused-vars */
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CurrencyNotFoundError,
  DuplicateRulePrecedenceError,
  InvalidRuleConfigurationError,
  ItemNotActiveError,
  ItemNotFoundError,
  PriceRuleNotFoundError,
  UnitNotFoundError,
} from "../lib/errors.generated";
import { findRuleConflict, isActiveStatus, selectOne } from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface ActivatePurchasePriceRuleInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: ActivatePurchasePriceRuleInput,
  ctx: CommandContext,
) {
  const purchasePriceRule = await selectOne(db, "PurchasePriceRule", "id", input.id, true);
  if (!purchasePriceRule) {
    return err(new PriceRuleNotFoundError(input.id));
  }
  if (purchasePriceRule.status === "ACTIVE") {
    return ok({ purchasePriceRule });
  }

  const itemId = purchasePriceRule.itemId as string;
  const currencyId = purchasePriceRule.currencyId as string;
  const unitId = purchasePriceRule.unitId as string;
  const item = await selectOne(db, "Item", "id", itemId);
  if (!item) {
    return err(new ItemNotFoundError(itemId));
  }
  if (!isActiveStatus(item.status as string | null)) {
    return err(new ItemNotActiveError(itemId));
  }
  if (!(await selectOne(db, "Currency", "id", currencyId))) {
    return err(new CurrencyNotFoundError(currencyId));
  }
  if (!(await selectOne(db, "Unit", "id", unitId))) {
    return err(new UnitNotFoundError(unitId));
  }

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

  const conflictingRule = await findRuleConflict(db, {
    itemId,
    currencyId,
    unitId,
    minimumQuantity: purchasePriceRule.minimumQuantity as number,
    effectiveFrom: purchasePriceRule.effectiveFrom as Date,
  });
  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 });
}
