import axios from 'axios';

const API_BASE = '/api';

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

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

// Auth endpoints
export const auth = {
  login: (username, password) =>
    apiClient.post('/auth/login', { username, password }),
  verify: () =>
    apiClient.post('/auth/verify'),
};

// Posts endpoints
export const posts = {
  getAll: (params) =>
    apiClient.get('/posts', { params }),
  getBySlug: (categorySlug, postSlug) =>
    apiClient.get(`/posts/${categorySlug}/${postSlug}`),
  create: (data) =>
    apiClient.post('/posts', data),
  update: (id, data) =>
    apiClient.put(`/posts/${id}`, data),
  publish: (id) =>
    apiClient.post(`/posts/${id}/publish`),
  delete: (id) =>
    apiClient.delete(`/posts/${id}`),
  getAllAdmin: () =>
    apiClient.get('/posts/admin/all'),
  getByIdAdmin: (id) =>
    apiClient.get(`/posts/admin/${id}`),
};

// Categories endpoints
export const categories = {
  getAll: () =>
    apiClient.get('/categories'),
  getBySlug: (slug) =>
    apiClient.get(`/categories/${slug}`),
  create: (data) =>
    apiClient.post('/categories', data),
  update: (id, data) =>
    apiClient.put(`/categories/${id}`, data),
  delete: (id) =>
    apiClient.delete(`/categories/${id}`),
};

// Media endpoints
export const media = {
  getAll: () =>
    apiClient.get('/media'),
  upload: (file, altText) => {
    const formData = new FormData();
    formData.append('image', file);
    formData.append('alt_text', altText);
    return apiClient.post('/media/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
  },
  update: (id, data) =>
    apiClient.put(`/media/${id}`, data),
  delete: (id) =>
    apiClient.delete(`/media/${id}`),
};

// Settings endpoints
export const settings = {
  getAll: () =>
    apiClient.get('/settings'),
  update: (key, value) =>
    apiClient.put(`/settings/${key}`, { value }),
  testTelegram: (botToken, chatId) =>
    apiClient.post('/settings/telegram/test', {
      telegram_bot_token: botToken,
      telegram_chat_id: chatId,
    }),
};
