import axios from 'axios'

const API_URL = import.meta.env.VITE_API_URL || (
  import.meta.env.PROD
    ? 'https://api-staging.echoesoftheash.com'
    : 'http://localhost:8000'
)

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

// Add request interceptor to include language preference
api.interceptors.request.use((config) => {
  const language = localStorage.getItem('i18nextLng') || 'en'
  config.headers['Accept-Language'] = language
  return config
})

// Add token to requests if it exists
const token = localStorage.getItem('token')
if (token) {
  api.defaults.headers.common['Authorization'] = `Bearer ${token}`
}

// Types
export interface Account {
  id: number
  email: string
  account_type: 'web' | 'steam'
  premium_expires_at: string | null
  created_at: string
  last_login_at: string
}

export interface Character {
  id: number
  account_id: number
  name: string
  avatar_data: any
  level: number
  xp: number
  hp: number
  max_hp: number
  stamina: number
  max_stamina: number
  strength: number
  agility: number
  endurance: number
  intellect: number
  unspent_points: number
  location_id: number
  is_dead: boolean
  created_at: string
  last_played_at: string
  weight: number
  max_weight: number
  volume: number
  max_volume: number
}

export interface LoginResponse {
  access_token: string
  token_type: string
  account: Account
  characters: Character[]
  needs_character_creation?: boolean
}

export interface RegisterResponse {
  access_token: string
  token_type: string
  account: Account
  characters: Character[]
  needs_character_creation: boolean
}

export interface CharacterSelectResponse {
  access_token: string
  token_type: string
  character: Character
}

// Auth API
export const authApi = {
  register: async (email: string, password: string): Promise<RegisterResponse> => {
    const response = await api.post('/api/auth/register', { email, password })
    return response.data
  },

  login: async (email: string, password: string): Promise<LoginResponse> => {
    const response = await api.post('/api/auth/login', { email, password })
    return response.data
  },

  getAccount: async (): Promise<{ account: Account; characters: Character[] }> => {
    const response = await api.get('/api/auth/account')
    return response.data
  },

  changeEmail: async (currentPassword: string, newEmail: string): Promise<{ message: string; new_email: string }> => {
    const response = await api.post('/api/auth/change-email', {
      current_password: currentPassword,
      new_email: newEmail
    })
    return response.data
  },

  changePassword: async (currentPassword: string, newPassword: string): Promise<{ message: string }> => {
    const response = await api.post('/api/auth/change-password', {
      current_password: currentPassword,
      new_password: newPassword
    })
    return response.data
  },

  steamLogin: async (steamId: string, steamName: string): Promise<LoginResponse> => {
    const response = await api.post('/api/auth/steam-login', {
      steam_id: steamId,
      steam_name: steamName
    })
    return response.data
  },
}


// Character API
export const characterApi = {
  list: async (): Promise<Character[]> => {
    const response = await api.get('/api/characters')
    // API returns { characters: [...] } so extract the array
    return response.data.characters || response.data
  },

  create: async (data: {
    name: string
    strength: number
    agility: number
    endurance: number
    intellect: number
    avatar_data?: any
  }): Promise<Character> => {
    const response = await api.post('/api/characters', data)
    return response.data
  },

  select: async (characterId: number): Promise<CharacterSelectResponse> => {
    const response = await api.post('/api/characters/select', { character_id: characterId })
    return response.data
  },

  delete: async (characterId: number): Promise<void> => {
    await api.delete(`/api/characters/${characterId}`)
  },
}

export default api

