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

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

/**
 * Function: reactivateContactPerson
 *
 * Reactivates an INACTIVE contact person by setting status to ACTIVE.
 * Does NOT restore primary designation.
 */
export async function run(db: Transaction, input: ReactivateContactPersonInput) {
  const { id, from = ["INACTIVE"] } = input;

  // 1. Check contact exists
  const existing = await db
    .selectFrom("ContactPerson")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!existing) {
    return err(new ContactPersonNotFoundError(id));
  }

  // 2. Validate status transition
  if (!from.includes(existing.status)) {
    return err(new InvalidStateTransitionError(id));
  }

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

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