import { supabase } from '../config/supabase';

// Base URL already includes `/api` (see .env.example). All `endpoint` args below are paths like `/pantry/orders`.
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:5000/api';

const getAuthToken = async () => {
  const { data: { session } } = await supabase.auth.getSession();
  return session?.access_token || null;
};

const authFetch = async (endpoint: string, options: RequestInit = {}) => {
  const token = await getAuthToken();
  
  if (!token) {
    throw new Error('No authentication token found');
  }

  const response = await fetch(`${API_URL}${endpoint}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
      ...options.headers,
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ error: 'Request failed' }));
    throw new Error(error.error || `HTTP ${response.status}`);
  }

  return response.json();
};

// ====================
// INVENTORY API
// ====================

export const inventoryAPI = {
  getAll: () => authFetch('/pantry/inventory'),
  
  create: (data: {
    name: string;
    description?: string;
    quantity: number;
    unit?: string;
    expiryDate?: string;
    categoryId?: string;
    lowStockThreshold?: number;
    imageUrl?: string;
  }) => authFetch('/pantry/inventory', {
    method: 'POST',
    body: JSON.stringify(data),
  }),

  update: (id: string, data: any) => authFetch(`/pantry/inventory/${id}`, {
    method: 'PUT',
    body: JSON.stringify(data),
  }),

  delete: (id: string) => authFetch(`/pantry/inventory/${id}`, {
    method: 'DELETE',
  }),
};

// ====================
// ORDERS API
// ====================

export const ordersAPI = {
  getAll: () => authFetch('/pantry/orders'),

  create: (data: {
    name: string;
    quantity?: number;
    unit?: string;
    priority?: string;
    notes?: string;
    cartItems?: Array<{
      id: string;
      name: string;
      quantity: number;
      unit?: string;
      imageUrl?: string;
      categoryId?: string;
    }>;
  }) => authFetch('/pantry/orders', {
    method: 'POST',
    body: JSON.stringify(data),
  }),

  updateStatus: (id: string, status: 'pending' | 'ready' | 'picked-up') =>
    authFetch(`/pantry/orders/${id}/status`, {
      method: 'PATCH',
      body: JSON.stringify({ status }),
    }),

  schedule: (id: string, data: { pickupAtISO: string; pickupLocation: string }) =>
    authFetch(`/pantry/orders/${id}/schedule`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    }),
};

// ====================
// STATS API
// ====================

export const statsAPI = {
  get: () => authFetch('/pantry/stats'),
  getActivity: () => authFetch('/pantry/activity'),
  getAlerts: () => authFetch('/pantry/alerts'),
  getAnalytics: () => authFetch('/pantry/analytics'),
};

// ====================
// USERS API
// ====================

export const usersAPI = {
  getAll: () => authFetch('/user/all'),
  
  getById: (id: string) => authFetch(`/user/${id}`),

  update: (id: string, data: { fullName?: string; role?: string; email?: string }) =>
    authFetch(`/user/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    }),

  delete: (id: string) => authFetch(`/user/${id}`, {
    method: 'DELETE',
  }),
};

// ====================
// CATEGORIES API
// ====================

export const categoriesAPI = {
  getAll: () => authFetch('/pantry/categories'),
  
  create: (data: { name: string; description?: string; color?: string }) =>
    authFetch('/pantry/categories', {
      method: 'POST',
      body: JSON.stringify(data),
    }),
};

// ====================
// SETTINGS API
// ====================

export const settingsAPI = {
  get: () => authFetch('/settings'),
  
  update: (data: { 
    pantryName: string; 
    contactPhone?: string; 
    address?: string; 
    lowStockThreshold: number; 
    expiryWarningDays: number 
  }) =>
    authFetch('/settings', {
      method: 'PUT',
      body: JSON.stringify(data),
    }),
};

// ====================
// PICKUP API
// ====================

export const pickupAPI = {
  getAll: () => authFetch('/pantry/pickups'),
  
  updateStatus: (id: string, status: 'pending' | 'ready' | 'picked-up') =>
    authFetch(`/pantry/orders/${id}/status`, {
      method: 'PATCH',
      body: JSON.stringify({ status }),
    }),
};

