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

export interface ReactivateDepartmentInput {
  departmentId: string;
}

/**
 * Function: reactivateDepartment
 *
 * Re-enables a previously deactivated department, making it available
 * for new assignments.
 */
export async function run(db: Transaction, input: ReactivateDepartmentInput) {
  const { departmentId } = input;

  // 1. Find department
  const existing = await db
    .selectFrom("Department")
    .selectAll()
    .where("id", "=", departmentId)
    .forUpdate()
    .executeTakeFirst();

  if (!existing) {
    return err(new DepartmentNotFoundError(departmentId));
  }

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

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

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