import axios, { AxiosResponse } from 'axios';

// Dynamic API base URL - works for both development and production
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || `${window.location.origin}/api`;

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

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

// Response interceptor to handle token expiration
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('auth_token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export interface ApiResponse<T> {
  success: boolean;
  data?: T;
  message?: string;
  errors?: Record<string, string[]>;
  error_code?: string;
}

export interface User {
  id: number;
  name: string;
  email: string;
  email_verified_at?: string;
  created_at: string;
  updated_at: string;
}

export interface UserProfile {
  id: number;
  user_id: number;
  preferred_language: 'en' | 'ms';
  default_industry?: string;
  created_at: string;
  updated_at: string;
}

export interface NumerologyCalculation {
  name: string;
  birthdate: string;
  industry?: string;
  L5: number[];
  L6: number[];
  L7: number[];
  L8: number[];
  L9: number[];
  root_number: number;
}

export interface RootInterpretation {
  title: string;
  traits: string;
  element: string;
  strengths: string;
  challenges: string;
  desires: string;
  career: string;
}

export interface SWOTCombination {
  sequence: string;
  base_combo: string;
  label: 'S' | 'W' | 'O' | 'T';
  description: string;
  cells: [number, number][];
}

export interface BusinessGuidance {
  element_category: string;
  suitable_businesses: string;
  industry_specific?: string;
}

export interface LearningStyle {
  style: string;
  approach: string;
}

export interface CalculationResult {
  calculation: NumerologyCalculation;
  interpretation: RootInterpretation;
  swot_combinations: SWOTCombination[];
  business_guidance: BusinessGuidance;
  learning_style: LearningStyle;
}

export interface SavedCalculation extends NumerologyCalculation {
  id: number;
  user_id: number;
  swot_combinations: SWOTCombination[];
  created_at: string;
  updated_at: string;
}

export default api;