const BACKEND_URL = import.meta.env.PUBLIC_MEDUSA_BACKEND_URL;
const PUBLISHABLE_KEY = import.meta.env.PUBLIC_MEDUSA_PUBLISHABLE_KEY;

export async function medusaFetch(path: string, init?: RequestInit) {
  const res = await fetch(`${BACKEND_URL}${path}`, {
    ...init,
    headers: {
      "Content-Type": "application/json",
      "x-publishable-api-key": PUBLISHABLE_KEY,
      ...init?.headers,
    },
  });

  const body = await res.json().catch(() => ({}));

  if (!res.ok) {
    throw new Error(body?.message || `Medusa request failed: ${path} (${res.status})`);
  }

  return body;
}

export interface MedusaVariant {
  id: string;
  title: string;
  calculated_price?: { calculated_amount: number; currency_code: string };
  metadata?: { net_weight_grams?: number } | null;
}

export interface MedusaProduct {
  id: string;
  title: string;
  handle: string;
  description: string | null;
  thumbnail: string | null;
  images?: { id: string; url: string }[];
  variants: MedusaVariant[];
  metadata?: { delivery_time?: string; category?: string } | null;
}

// Pulls in the custom metadata (delivery time, category, net fill weight) on
// top of Medusa's default product/variant fields.
const PRODUCT_FIELDS = "*variants.calculated_price,+metadata,+variants.metadata";

export async function listProducts(regionId?: string): Promise<MedusaProduct[]> {
  const params = new URLSearchParams({ fields: PRODUCT_FIELDS });
  if (regionId) params.set("region_id", regionId);
  const data = await medusaFetch(`/store/products?${params}`);
  return data.products;
}

export async function getProductByHandle(handle: string, regionId?: string): Promise<MedusaProduct | null> {
  const params = new URLSearchParams({ handle, fields: PRODUCT_FIELDS });
  if (regionId) params.set("region_id", regionId);
  const data = await medusaFetch(`/store/products?${params}`);
  return data.products[0] ?? null;
}

export interface MedusaRegion {
  id: string;
  currency_code: string;
}

export async function getDefaultRegion(): Promise<MedusaRegion> {
  const data = await medusaFetch("/store/regions");
  return data.regions[0];
}
