/**
 * 订单查询 Hook（React Query 统一封装）
 *
 * 统一处理 loading / error / 缓存，避免每个页面重复 useEffect+useState 模板。
 */

import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";

export interface OrderRow {
  id: string;
  order_number: string;
  total_amount: number;
  status: string;
  shipping_address: string | null;
  tracking_number: string | null;
  shipped_at: string | null;
  notes: string | null;
  created_at: string;
  updated_at: string;
}

export interface OrderItemRow {
  id: string;
  product_id: string;
  quantity: number;
  unit_price: number;
  products?: { name: string; image_url: string | null } | null;
}

export interface OrderCouponRow {
  id: string;
  coupon_id: string;
  coupons?: {
    name: string;
    code: string;
    type: string;
    discount_value: number;
  } | null;
}

export const ordersKeys = {
  all: ["orders"] as const,
  list: (userId: string | undefined) => ["orders", "list", userId] as const,
  items: (orderId: string) => ["orders", "items", orderId] as const,
  coupon: (orderId: string) => ["orders", "coupon", orderId] as const,
};

export function useOrdersList(userId: string | undefined) {
  return useQuery({
    queryKey: ordersKeys.list(userId),
    enabled: !!userId,
    queryFn: async (): Promise<OrderRow[]> => {
      const { data, error } = await supabase
        .from("orders")
        .select("*")
        .eq("user_id", userId!)
        .order("created_at", { ascending: false });
      if (error) throw error;
      return data || [];
    },
    staleTime: 30_000,
  });
}

export function useOrderItems(orderId: string | undefined) {
  return useQuery({
    queryKey: ordersKeys.items(orderId ?? ""),
    enabled: !!orderId,
    queryFn: async (): Promise<OrderItemRow[]> => {
      const { data, error } = await supabase
        .from("order_items")
        .select(`*, products ( name, image_url )`)
        .eq("order_id", orderId!);
      if (error) throw error;
      return data || [];
    },
  });
}

export function useOrderCoupon(orderId: string | undefined) {
  return useQuery({
    queryKey: ordersKeys.coupon(orderId ?? ""),
    enabled: !!orderId,
    queryFn: async (): Promise<OrderCouponRow | null> => {
      const { data, error } = await supabase
        .from("user_coupons")
        .select(`id, coupon_id, coupons ( name, code, type, discount_value )`)
        .eq("order_id", orderId!)
        .eq("status", "used")
        .maybeSingle();
      if (error) throw error;
      return data;
    },
  });
}
