const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';

interface ApiOptions {
  method?: string;
  body?: unknown;
  headers?: Record<string, string>;
}

class ApiError extends Error {
  status: number;
  data: unknown;
  constructor(message: string, status: number, data?: unknown) {
    super(message);
    this.status = status;
    this.data = data;
  }
}

async function request<T = unknown>(endpoint: string, options: ApiOptions = {}): Promise<T> {
  const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;

  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...options.headers,
  };
  if (token) headers['Authorization'] = `Bearer ${token}`;

  const res = await fetch(`${API_BASE}${endpoint}`, {
    method: options.method || 'GET',
    headers,
    body: options.body ? JSON.stringify(options.body) : undefined,
  });

  const data = await res.json().catch(() => null);

  if (!res.ok) {
    if (res.status === 401 && typeof window !== 'undefined') {
      localStorage.removeItem('token');
      localStorage.removeItem('refreshToken');
      window.location.href = '/login';
    }
    throw new ApiError(data?.message || 'API Error', res.status, data);
  }

  return data as T;
}

export const api = {
  get: <T = unknown>(url: string) => request<T>(url),
  post: <T = unknown>(url: string, body?: unknown) => request<T>(url, { method: 'POST', body }),
  put: <T = unknown>(url: string, body?: unknown) => request<T>(url, { method: 'PUT', body }),
  delete: <T = unknown>(url: string) => request<T>(url, { method: 'DELETE' }),
};

// Auth
export const authApi = {
  login: (email: string, password: string) =>
    api.post<{ success: boolean; data: { accessToken: string; refreshToken: string } }>('/auth/login', { email, password }),
  register: (data: { name: string; email: string; password: string; slug?: string }) =>
    api.post('/auth/register', data),
  me: () => api.get<{ success: boolean; data: { id: string; name: string; email: string; plan: string; slug: string } }>('/auth/me'),
};

// Products
export const productApi = {
  list: (page = 1, limit = 20) => api.get(`/products?page=${page}&limit=${limit}`),
  create: (data: Record<string, unknown>) => api.post('/products', data),
  update: (id: string, data: Record<string, unknown>) => api.put(`/products/${id}`, data),
  delete: (id: string) => api.delete(`/products/${id}`),
};

// Sessions
export const sessionApi = {
  start: (data: { igLiveVideoId: string; title: string }) => api.post('/sessions/start', data),
  end: (id: string) => api.put(`/sessions/${id}/end`),
  stats: (id: string) => api.get(`/sessions/${id}/stats`),
};

// Auctions
export const auctionApi = {
  activate: (data: {
    productId: string;
    liveSessionId: string;
    mode: string;
    startingPrice: number;
    minBidIncrement?: number;
    timeLimitSeconds?: number;
  }) => api.post('/auctions/activate', data),
  close: (id: string) => api.put(`/auctions/${id}/close`),
  extend: (id: string, seconds: number) => api.put(`/auctions/${id}/extend`, { seconds }),
  bids: (id: string) => api.get(`/auctions/${id}/bids`),
};

// Users
export const userApi = {
  list: (page = 1, limit = 20) => api.get(`/users?page=${page}&limit=${limit}`),
  history: (id: string) => api.get(`/users/${id}/history`),
  block: (id: string) => api.put(`/users/${id}/block`),
};

// Tenant
export const tenantApi = {
  update: (data: Record<string, unknown>) => api.put('/tenant', data),
  stats: () => api.get('/tenant/stats'),
  regenerateWebhookSecret: () => api.post('/tenant/webhook-secret'),
};

export { ApiError };
