import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useAuthStore } from './authStore'
import { API_BASE_URL } from '@/config/api'

const API_URL = API_BASE_URL

export const useTimeStore = defineStore('time', () => {
  const entries = ref([])
  const currentEntry = ref(null)
  
  /**
   * API-Request mit Auth-Header
   */
  const fetchWithAuth = async (url, options = {}) => {
    const authStore = useAuthStore()
    const headers = authStore.getAuthHeaders()
    
    const response = await fetch(url, {
      ...options,
      headers: {
        ...headers,
        ...options.headers
      }
    })

    // Bei 401 Unauthorized -> Logout
    if (response.status === 401) {
      authStore.clearAuth()
      window.location.href = '/login'
      throw new Error('Session abgelaufen')
    }

    return response
  }

  const fetchEntries = async () => {
    try {
      const response = await fetchWithAuth(`${API_URL}/time-entries`)
      const data = await response.json()
      entries.value = data
      
      // Finde laufenden Eintrag
      currentEntry.value = data.find(entry => entry.isRunning) || null
    } catch (error) {
      console.error('Fehler beim Laden der Einträge:', error)
    }
  }

  const startTimer = async (entryData) => {
    try {
      const response = await fetchWithAuth(`${API_URL}/time-entries`, {
        method: 'POST',
        body: JSON.stringify(entryData)
      })
      
      const newEntry = await response.json()
      currentEntry.value = newEntry
      entries.value.unshift(newEntry)
    } catch (error) {
      console.error('Fehler beim Starten des Timers:', error)
    }
  }

  const stopTimer = async () => {
    if (!currentEntry.value) return
    
    try {
      const response = await fetchWithAuth(`${API_URL}/time-entries/${currentEntry.value.id}`, {
        method: 'PUT',
        body: JSON.stringify({
          endTime: new Date().toISOString()
        })
      })
      
      const updatedEntry = await response.json()
      
      // Aktualisiere Eintrag in Liste
      const index = entries.value.findIndex(e => e.id === updatedEntry.id)
      if (index !== -1) {
        entries.value[index] = updatedEntry
      }
      
      currentEntry.value = null
    } catch (error) {
      console.error('Fehler beim Stoppen des Timers:', error)
    }
  }

  const deleteEntry = async (id) => {
    try {
      await fetchWithAuth(`${API_URL}/time-entries/${id}`, {
        method: 'DELETE'
      })
      
      entries.value = entries.value.filter(entry => entry.id !== id)
      
      if (currentEntry.value && currentEntry.value.id === id) {
        currentEntry.value = null
      }
    } catch (error) {
      console.error('Fehler beim Löschen des Eintrags:', error)
    }
  }

  const fetchStats = async () => {
    try {
      const response = await fetchWithAuth(`${API_URL}/time-entries/stats/summary`)
      return await response.json()
    } catch (error) {
      console.error('Fehler beim Laden der Statistiken:', error)
      return {}
    }
  }

  return {
    entries,
    currentEntry,
    fetchEntries,
    startTimer,
    stopTimer,
    deleteEntry,
    fetchStats
  }
})

