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 DeactivateSiteInput {
  siteId: string;
}

/**
 * Function: deactivateSite
 *
 * Transitions a site from an active state to inactive, preventing it from
 * being used in new operational assignments.
 */
export async function run(db: Transaction, input: DeactivateSiteInput) {
  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 ACTIVE
  if (existingSite.status !== "ACTIVE") {
    return err(new InvalidStateError(siteId));
  }

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

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