import axios from 'axios';

const api = axios.create({
  baseURL: '/api',
  withCredentials: true,
});

// Intercepteur pour gérer les erreurs d'auth
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('dashboard_token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response && error.response.status === 401) {
      localStorage.removeItem('dashboard_token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export default api;

// Auth
export const login = (username, password) =>
  api.post('/auth/login', { username, password });

export const logout = () => api.post('/auth/logout');

export const getMe = () => api.get('/auth/me');

// Apps
export const getApps = () => api.get('/apps');
export const getApp = (id) => api.get(`/apps/${id}`);
export const checkApp = (id) => api.post(`/apps/${id}/check`);
export const deployApp = (id) => api.post(`/apps/${id}/deploy`);
export const getAppLogs = (id, tail = 100) =>
  api.get(`/apps/${id}/logs`, { params: { tail } });

// App creation
export const getAvailableStacks = () => api.get('/apps-config/stacks');
export const createApp = (formData) =>
  api.post('/apps-config/create', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 600000, // 10 minutes timeout
  });

// Deployments
export const getDeployments = (appId) =>
  api.get('/deployments', { params: { appId } });

// Gitea
export const getGiteaRepos = () => api.get('/gitea/repos');
export const getGiteaCommits = (owner, repo) =>
  api.get(`/gitea/repos/${owner}/${repo}/commits`);

// Docker
export const getContainers = () => api.get('/docker/containers');

// System
export const getSystemInfo = () => api.get('/system/info');
export const getServerMetrics = () => api.get('/system/metrics');

// Container control
export const startApp = (id) => api.post(`/apps/${id}/start`);
export const stopApp = (id) => api.post(`/apps/${id}/stop`);
export const restartApp = (id) => api.post(`/apps/${id}/restart`);
