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

export interface DeactivateContactPersonInput {
  id: string;
}

/**
 * Function: deactivateContactPerson
 *
 * Deactivates a contact person by setting status to INACTIVE. If the contact
 * is primary, removes the primary designation (sets isPrimary=false).
 */
export async function run(db: Transaction, input: DeactivateContactPersonInput) {
  const { id } = 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
  const nextStatus = contactPersonLifecycle.tryTransition(existing.status, "deactivate");
  if (!nextStatus) {
    return err(new InvalidStateTransitionError(id));
  }

  // 3. Build update: set INACTIVE, remove primary if needed
  const updateValues: Record<string, unknown> = {
    status: nextStatus,
  };

  if (existing.isPrimary) {
    updateValues.isPrimary = false;
  }

  const contact = await db
    .updateTable("ContactPerson")
    .set(updateValues)
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ contact });
}
