import axios from 'axios';

const API_BASE_URL = import.meta.env.DEV ? '/api' : 'http://localhost/awtf/public/api';

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

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

// Handle responses
api.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    }
    throw error;
  }
);

// Auth API
export const authAPI = {
  register: (data) => api.post('/auth/register', data),
  login: (email, password) => api.post('/auth/login', { email, password }),
  getInvitation: (token) => api.get(`/auth/invitations/${token}`),
  profile: () => api.get('/auth/profile'),
  updateProfile: (data) => api.put('/auth/profile', data),
  changePassword: (data) => api.post('/auth/change-password', data),
  requestSmsToken: (roll_no, phone) => api.post('/auth/sms-token/request', { roll_no, phone }),
  verifySmsToken: (roll_no, token) => api.post('/auth/sms-token/verify', { roll_no, token }),
};

// Members API
export const membersAPI = {
  list: (page = 1, limit = 20, search = '', status = '') =>
    api.get('/members', { params: { page, limit, search, status } }),
  create: (data) => api.post('/members', data),
  sendInvitation: (data) => api.post('/members/invite', data),
  me: () => api.get('/members/me'),
  get: (id) => api.get(`/members/${id}`),
  update: (id, data) => api.put(`/members/${id}`, data),
  delete: (id) => api.delete(`/members/${id}`),
  search: (q) => api.get('/members/search', { params: { q } }),
  statuses: () => api.get('/members/statuses'),
  stats: () => api.get('/members/stats'),
  deceasedStats: () => api.get('/members/stats', { params: { type: 'deceased' } }),
  generatePublicUpdateLink: (id) => api.post(`/members/${id}/public-link`),
};

// Beneficiaries API
export const beneficiariesAPI = {
  getByMember: (memberId) => api.get(`/beneficiaries/member/${memberId}`),
  create: (data) => api.post('/beneficiaries', data),
  get: (id) => api.get(`/beneficiaries/${id}`),
  update: (id, data) => api.put(`/beneficiaries/${id}`, data),
  delete: (id) => api.delete(`/beneficiaries/${id}`),
  validate: (memberId) => api.post(`/beneficiaries/validate/${memberId}`),
};

export const publicBeneficiariesAPI = {
  get: (token) => api.get(`/beneficiaries/public/${token}`),
  create: (token, data) => api.post('/beneficiaries/public', { token, ...data }),
  update: (id, token, data) => api.put(`/beneficiaries/public/${id}`, { token, ...data }),
  validate: (token) => api.post('/beneficiaries/public/validate', { token }),
};

// Payments API
export const paymentsAPI = {
  list: (page = 1, limit = 20, status = '') => 
    api.get('/payments', { params: { page, limit, status } }),
  getByMember: (memberId) => api.get(`/payments/member/${memberId}`),
  create: (data) => api.post('/payments', data),
  get: (id) => api.get(`/payments/${id}`),
  generateQR: (id) => api.post(`/payments/qr/${id}`),
  markAsPaid: (id) => api.post(`/payments/mark-paid/${id}`),
  getOutstanding: () => api.get('/payments/outstanding'),
  stats: (year) => api.get('/payments/stats', { params: { year } }),
};

// Claims API
export const claimsAPI = {
  list: (page = 1, limit = 20, status = '') => 
    api.get('/claims', { params: { page, limit, status } }),
  getByMember: (memberId) => api.get(`/claims/member/${memberId}`),
  create: (data) => api.post('/claims', data),
  get: (id) => api.get(`/claims/${id}`),
  approve: (id) => api.post(`/claims/approve/${id}`),
  reject: (id, data) => api.post(`/claims/reject/${id}`, data),
  markAsPaid: (id) => api.post(`/claims/mark-paid/${id}`),
  stats: (year) => api.get('/claims/stats', { params: { year } }),
};

export default api;
