import type { Order, SellerEarning } from "@/types/marketplace";

const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

export const sellerService = {
  async getDashboardStats() {
    const res = await fetch(`${BASE_URL}/api/marketplace/seller/dashboard`);
    if (!res.ok) throw new Error("Failed to fetch dashboard stats");
    return res.json();
  },

  async getSellerOrders(
    status?: string,
    page = 1
  ): Promise<{ orders: Order[]; total: number }> {
    const params = new URLSearchParams({ page: String(page) });
    if (status) params.set("status", status);
    const res = await fetch(
      `${BASE_URL}/api/marketplace/seller/orders?${params}`
    );
    if (!res.ok) throw new Error("Failed to fetch seller orders");
    return res.json();
  },

  async updateOrderStatus(orderId: string, status: string): Promise<Order> {
    const res = await fetch(
      `${BASE_URL}/api/marketplace/seller/orders/${orderId}/status`,
      {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status }),
      }
    );
    if (!res.ok) throw new Error("Failed to update order status");
    return res.json();
  },

  async getEarnings(
    period?: "week" | "month" | "year"
  ): Promise<{ earnings: SellerEarning[]; total: number; pending: number }> {
    const params = new URLSearchParams();
    if (period) params.set("period", period);
    const res = await fetch(
      `${BASE_URL}/api/marketplace/seller/earnings?${params}`
    );
    if (!res.ok) throw new Error("Failed to fetch earnings");
    return res.json();
  },

  async withdrawEarnings(amount: number, bankAccountId: string): Promise<void> {
    const res = await fetch(`${BASE_URL}/api/marketplace/seller/withdraw`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ amount, bankAccountId }),
    });
    if (!res.ok) throw new Error("Failed to initiate withdrawal");
  },
};
