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

export interface SetDefaultPartnerAddressInput {
  id: string;
}

/**
 * Function: setDefaultPartnerAddress
 *
 * Sets the specified address as the default for its address type.
 * Unsets isDefault on all other addresses of the same type and partner.
 */
export async function run(db: Transaction, input: SetDefaultPartnerAddressInput) {
  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. Unset isDefault on all other addresses of same type and partner
  await db
    .updateTable("PartnerAddress")
    .set({ isDefault: false })
    .where("partnerId", "=", address.partnerId)
    .where("addressType", "=", address.addressType)
    .where("isDefault", "=", true)
    .execute();

  // 3. Set isDefault on this address
  const updatedAddress = await db
    .updateTable("PartnerAddress")
    .set({ isDefault: true })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ address: updatedAddress });
}
