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

export interface ReactivateProductInput {
  id: string;
  from?: string[];
}

/**
 * Function: reactivateProduct
 *
 * Transitions a product from ARCHIVED to ACTIVE.
 */
export async function run(db: Transaction, input: ReactivateProductInput) {
  const { id } = input;
  const validFrom = input.from ?? ["ARCHIVED"];

  const product = await db
    .selectFrom("Product")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!product) {
    return err(new ProductNotFoundError(id));
  }

  if (!validFrom.includes(product.status)) {
    return err(new InvalidStateTransitionError(id));
  }

  const updated = await db
    .updateTable("Product")
    .set({ status: "ACTIVE", updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

  return ok({ product: updated! });
}
