import { Transaction } from "../generated/kysely-tailordb";
import { CurrencyNotFoundError } from "../lib/errors.generated";
import { ok, err } from "@tailor-platform/erp-kit/module";

export interface ActivateCurrencyInput {
  currencyId: string;
}

/**
 * Function: activateCurrency
 *
 * Re-enables a previously deactivated currency, making it available
 * for new transactions.
 */
export async function run(db: Transaction, input: ActivateCurrencyInput) {
  // 1. Find currency by ID
  const currency = await db
    .selectFrom("Currency")
    .selectAll()
    .where("id", "=", input.currencyId)
    .forUpdate()
    .executeTakeFirst();

  // 2. If not found, throw error
  if (!currency) {
    return err(new CurrencyNotFoundError(input.currencyId));
  }

  // 3. If already active, return currency (idempotent)
  if (currency.isActive) {
    return ok({ currency });
  }

  // 4. Update isActive = true
  const updatedCurrency = await db
    .updateTable("Currency")
    .set({
      isActive: true,
      updatedAt: new Date(),
    })
    .where("id", "=", input.currencyId)
    .returningAll()
    .executeTakeFirst();

  // 5. Return updated currency
  return ok({ currency: updatedCurrency! });
}
