import axios from 'axios';
import * as SecureStore from 'expo-secure-store';
import { config } from '../constants/config';

const SESSION_KEY = 'session_id';

export const api = axios.create({
  baseURL: config.API_BASE_URL,
  timeout: 10000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor - restore session cookie from SecureStore
api.interceptors.request.use(
  async (axiosConfig) => {
    const session = await SecureStore.getItemAsync(SESSION_KEY);
    if (session) {
      axiosConfig.headers.Cookie = session;
    }
    return axiosConfig;
  },
  (error) => Promise.reject(error)
);

// Response interceptor - capture and persist session cookie from responses
api.interceptors.response.use(
  (response) => {
    const setCookie = response.headers['set-cookie'];
    if (setCookie) {
      const cookieStr = Array.isArray(setCookie) ? setCookie[0] : setCookie;
      const sessionId = cookieStr.split(';')[0];
      SecureStore.setItemAsync(SESSION_KEY, sessionId);
    }
    return response;
  },
  async (error) => {
    if (error.response?.status === 401) {
      await SecureStore.deleteItemAsync(SESSION_KEY);
    }
    return Promise.reject(error);
  }
);

export default api;
