import axios, { AxiosResponse } from 'axios';
import {
  AuthResponse,
  RegisterRequest,
  LoginRequest,
  Counter,
  CounterWithStats,
  CounterEntry,
  CreateCounterRequest,
  UpdateCounterRequest,
  IncrementRequest,
  CounterStats,
  User,
} from '../types';
import { getApiUrl, logConfig } from '../config/environment';

// Initialize configuration
logConfig();
const API_BASE_URL = getApiUrl();

// Create axios instance
const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Add auth token to requests
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Handle auth errors
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// Auth API
export const authAPI = {
  register: (data: RegisterRequest): Promise<AxiosResponse<AuthResponse>> =>
    api.post('/auth/register', data),
  
  login: (data: LoginRequest): Promise<AxiosResponse<AuthResponse>> =>
    api.post('/auth/login', data),
  
  getCurrentUser: (): Promise<AxiosResponse<User>> =>
    api.get('/auth/me'),
};

// Counters API
export const countersAPI = {
  getCounters: (search?: string): Promise<AxiosResponse<CounterWithStats[]>> => {
    const params = search ? { search } : {};
    return api.get('/counters', { params });
  },
  
  getCounter: (id: number): Promise<AxiosResponse<CounterWithStats>> =>
    api.get(`/counters/${id}`),
  
  createCounter: (data: CreateCounterRequest): Promise<AxiosResponse<Counter>> =>
    api.post('/counters', data),
  
  updateCounter: (id: number, data: UpdateCounterRequest): Promise<AxiosResponse<Counter>> =>
    api.put(`/counters/${id}`, data),
  
  deleteCounter: (id: number): Promise<AxiosResponse<{ message: string }>> =>
    api.delete(`/counters/${id}`),
  
  incrementCounter: (id: number, data: IncrementRequest): Promise<AxiosResponse<CounterEntry>> =>
    api.post(`/counters/${id}/increment`, data),
  
  getCounterEntries: (id: number, startDate?: string, endDate?: string): Promise<AxiosResponse<CounterEntry[]>> => {
    const params: any = {};
    if (startDate) params.start_date = startDate;
    if (endDate) params.end_date = endDate;
    return api.get(`/counters/${id}/entries`, { params });
  },
  
  getCounterStats: (id: number): Promise<AxiosResponse<CounterStats>> =>
    api.get(`/counters/${id}/stats`),
};

export default api;
