import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';

// ← Change this to your school server path
const BASE = 'https://yourdomain.school.edu/slowmail-api/api/index.php';

const api = axios.create({ baseURL: BASE });

api.interceptors.request.use(async (config) => {
  const token = await AsyncStorage.getItem('token');
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

// Convenience wrappers that build the ?route= URL
export const get  = (route: string, params = {}) =>
  api.get('', { params: { route, ...params } });

export const post = (route: string, data = {}, params = {}) =>
  api.post('', data, { params: { route, ...params } });

export default api;

export const saveAuth = async (token: string, user: object) => {
  await AsyncStorage.setItem('token', token);
  await AsyncStorage.setItem('user', JSON.stringify(user));
};

export const clearAuth = async () => {
  await AsyncStorage.removeItem('token');
  await AsyncStorage.removeItem('user');
};

export const getUser = async () => {
  const u = await AsyncStorage.getItem('user');
  return u ? JSON.parse(u) : null;
};
