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

export interface DeleteContactPersonInput {
  id: string;
}

/**
 * Function: deleteContactPerson
 *
 * Permanently deletes a contact person. Contact must be ACTIVE and must
 * NOT be the primary contact.
 */
export async function run(db: Transaction, input: DeleteContactPersonInput) {
  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. Contact must be ACTIVE
  if (existing.status !== "ACTIVE") {
    return err(new ContactNotActiveError(id));
  }

  // 3. Contact must NOT be primary
  if (existing.isPrimary) {
    return err(new ContactIsPrimaryError(id));
  }

  // 4. Delete the contact
  await db.deleteFrom("ContactPerson").where("id", "=", id).execute();

  return ok({ id });
}
