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

export interface DeletePartnerAddressInput {
  id: string;
}

export interface AddressReferenceChecker {
  isAddressReferenced: (db: Transaction, addressId: string) => Promise<boolean>;
}

/**
 * Function: deletePartnerAddress
 *
 * Permanently removes a partner address. Addresses referenced on
 * existing transactions cannot be deleted. Deleting a default address
 * does not auto-promote another address to default.
 */
export async function run(
  db: Transaction,
  input: DeletePartnerAddressInput,
  _ctx: CommandContext,
  referenceChecker?: AddressReferenceChecker,
) {
  const { id } = input;

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

  if (!address) {
    return err(new AddressNotFoundError(id));
  }

  // 2. Check if address is referenced on transactions
  if (referenceChecker) {
    const inUse = await referenceChecker.isAddressReferenced(db, id);
    if (inUse) {
      return err(new AddressInUseError(id));
    }
  }

  // 3. Delete address
  await db.deleteFrom("PartnerAddress").where("id", "=", id).execute();

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