"use client";

import { useQuery } from "convex/react";
import { useMemo } from "react";
import { api } from "../../../../../convex/_generated/api";
import type { CheckoutAddress } from "./types";

/**
 * Fetches the authenticated user's shipping addresses for the checkout flow.
 *
 * Internally calls `api.checkout.getShippingAddresses` (reactive).
 * Maps Convex documents to `CheckoutAddress`, coercing
 * `isValidated: undefined` → `false` for backward compatibility.
 */
export function useShippingAddresses(): {
  addresses: CheckoutAddress[];
  isLoading: boolean;
} {
  const data = useQuery(api.checkout.getShippingAddresses);

  return useMemo(() => {
    if (data === undefined) {
      return { addresses: [], isLoading: true };
    }

    const addresses: CheckoutAddress[] = data.map((doc) => ({
      id: doc._id,
      type: doc.type as "shipping" | "billing",
      fullName: doc.fullName,
      firstName: doc.firstName,
      lastName: doc.lastName,
      phone: doc.phone,
      addressLine1: doc.addressLine1,
      additionalInformation: doc.additionalInformation,
      city: doc.city,
      postalCode: doc.postalCode,
      country: doc.country,
      isDefault: doc.isDefault,
      isValidated: doc.isValidated ?? false,
    }));

    return { addresses, isLoading: false };
  }, [data]);
}
