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

export interface ReactivateSiteInput {
  siteId: string;
}

/**
 * Function: reactivateSite
 *
 * Transitions a site from an inactive state back to active, making it
 * available for operational assignments again.
 */
export async function run(db: Transaction, input: ReactivateSiteInput) {
  const { siteId } = input;

  // 1. Find site with forUpdate()
  const existingSite = await db
    .selectFrom("Site")
    .selectAll()
    .where("id", "=", siteId)
    .forUpdate()
    .executeTakeFirst();

  if (!existingSite) {
    return err(new SiteNotFoundError(siteId));
  }

  // 2. Check status is INACTIVE
  if (existingSite.status !== "INACTIVE") {
    return err(new InvalidStateError(siteId));
  }

  // 3. Set status ACTIVE, updatedAt
  const site = await db
    .updateTable("Site")
    .set({
      status: "ACTIVE",
      updatedAt: new Date(),
    })
    .where("id", "=", siteId)
    .returningAll()
    .executeTakeFirst();

  return ok({ site: site! });
}
