import { ok, err, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { PartnerAddressAddressType } from "../generated/enums";
import type { DB } from "../generated/kysely-tailordb";
import { NoAddressOfTypeError, NoDefaultAddressError } from "../lib/errors.generated";

export interface GetDefaultPartnerAddressInput {
  partnerId: string;
  addressType: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetDefaultPartnerAddressInput) {
  const addresses = await db
    .selectFrom("PartnerAddress")
    .selectAll()
    .where("partnerId", "=", input.partnerId)
    .where("addressType", "=", input.addressType as PartnerAddressAddressType)
    .execute();

  if (addresses.length === 0) {
    return err(new NoAddressOfTypeError(input.partnerId));
  }

  const defaultAddress = addresses.find((a) => a.isDefault);

  if (!defaultAddress) {
    return err(new NoDefaultAddressError(input.partnerId));
  }

  return ok({ partnerAddress: defaultAddress });
}
