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 SetPrimaryContactPersonInput {
  id: string;
}

/**
 * Function: setPrimaryContactPerson
 *
 * Sets a contact person as the primary contact for their partner. Unsets the
 * previous primary contact for the same partner. Contact must be ACTIVE.
 */
export async function run(db: Transaction, input: SetPrimaryContactPersonInput) {
  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 InvalidStateTransitionError(id));
  }

  // 3. Unset previous primary for same partner
  await db
    .updateTable("ContactPerson")
    .set({ isPrimary: false, updatedAt: new Date() })
    .where("partnerId", "=", existing.partnerId)
    .where("isPrimary", "=", true)
    .execute();

  // 4. Set this contact as primary
  const contact = await db
    .updateTable("ContactPerson")
    .set({
      isPrimary: true,
      updatedAt: new Date(),
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

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