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

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

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

  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: "ARCHIVED", updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

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