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

export interface DeletePartnerInput {
  id: string;
}

/**
 * Function: deletePartner
 *
 * Permanently removes a DRAFT business partner and all related records.
 * Only DRAFT partners can be deleted; ACTIVE and INACTIVE are preserved for audit trails.
 */
export async function run(db: Transaction, input: DeletePartnerInput) {
  const { id } = input;

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

  if (!partner) {
    return err(new PartnerNotFoundError(id));
  }

  // 2. Check status is DRAFT
  if (partner.status !== "DRAFT") {
    return err(new InvalidStateTransitionError(`${id} (status: ${partner.status})`));
  }

  // 3. Delete related records
  await db.deleteFrom("PartnerRole").where("partnerId", "=", id).execute();
  await db.deleteFrom("PartnerAddress").where("partnerId", "=", id).execute();
  await db.deleteFrom("PartnerBankAccount").where("partnerId", "=", id).execute();
  await db.deleteFrom("PartnerIdentification").where("partnerId", "=", id).execute();
  await db.deleteFrom("ContactPerson").where("partnerId", "=", id).execute();

  // 4. Delete partner
  await db.deleteFrom("BusinessPartner").where("id", "=", id).execute();

  return ok({ success: true as const });
}
