import axios from 'axios'
import type { Employee } from '@skillmate/shared'

const API_BASE_URL = (import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api'

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

// Auth interceptor
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

export const authApi = {
  login: async (email: string, password: string) => {
    const response = await api.post('/auth/login', { email, password })
    return response.data.data
  },
  logout: async () => {
    localStorage.removeItem('token')
  }
}

export const employeeApi = {
  getAll: async () => {
    // Hole vollständige Liste (berechtigt durch employees:read)
    const response = await api.get('/employees')
    return response.data.data
  },
  getById: async (id: string) => {
    const response = await api.get(`/employees/${id}`)
    return response.data.data
  },
  create: async (employee: Partial<Employee>) => {
    const response = await api.post('/employees', employee)
    return response.data
  },
  update: async (id: string, employee: Partial<Employee>) => {
    const response = await api.put(`/employees/${id}`, employee)
    return response.data.data
  },
  delete: async (id: string) => {
    await api.delete(`/employees/${id}`)
  },
  search: async (query: string) => {
    const response = await api.get(`/employees/search?q=${query}`)
    return response.data.data
  }
}

export const skillsApi = {
  searchBySkills: async (skills: string[]) => {
    const response = await api.post<Employee[]>('/skills/search', { skills })
    return response.data
  }
}

export { api }
export default api
