import { defineStore } from 'pinia'
import { useAuthStore } from '~/stores/auth'

export const useStaffTime = () => {
    const { $api, $dayjs } = useNuxtApp()
    const auth = useAuthStore()

    // ... (list Funktion bleibt gleich) ...
    const list = async (filter?: { user_id?: string, from?: string, to?: string }) => {
        // ... (Code wie zuvor)
        const from = filter?.from || $dayjs().startOf('month').format('YYYY-MM-DD')
        const to = filter?.to || $dayjs().endOf('month').format('YYYY-MM-DD')
        const targetUserId = filter?.user_id || auth.user.id
        const params = new URLSearchParams({ from, to, targetUserId })
        try {
            const spans = await $api(`/api/staff/time/spans?${params.toString()}`)
            return (spans || []).map((span: any) => {
                const start = $dayjs(span.startedAt)
                const end = span.endedAt ? $dayjs(span.endedAt) : $dayjs()
                return {
                    id: span.sourceEventIds && span.sourceEventIds.length > 0 ? span.sourceEventIds[0] : null,
                    eventIds: span.sourceEventIds || [],
                    state: span.status,
                    started_at: span.startedAt,
                    stopped_at: span.endedAt,
                    duration_minutes: end.diff(start, 'minute'),
                    user_id: targetUserId,
                    type: span.type,
                    description: span.description || span.payload?.description || ''
                }
            }).sort((a: any, b: any) => $dayjs(b.started_at).valueOf() - $dayjs(a.started_at).valueOf())
        } catch (error) {
            console.error("Fehler beim Laden:", error)
            return []
        }
    }

    /**
     * Startet "jetzt" (Live-Modus).
     * Kann optional eine Zeit empfangen (für manuelle Korrekturen),
     * aber wir nutzen dafür besser die createEntry Funktion unten.
     */
    const start = async (description = "Arbeitszeit", time?: string) => {

        console.log(auth.user)

        await $api('/api/staff/time/event', {
            method: 'POST',
            body: {
                eventtype: 'work_start',
                eventtime: time || new Date().toISOString(), // 💡 Fix: Zeit akzeptieren
                payload: { description },
                user_id: auth.user?.id
            }
        })
    }

    const stop = async () => {
        await $api('/api/staff/time/event', { method: 'POST', body: { eventtype: 'work_end', eventtime: new Date().toISOString(),
                user_id: auth.user?.id } })
    }

    const submit = async (entry: any) => {
        const ids = entry.eventIds || (entry.id ? [entry.id] : [entry]);
        if (!ids || ids.length === 0) return
        await $api('/api/staff/time/submit', { method: 'POST', body: { eventIds: ids } })
    }

    const approve = async (entry: any) => {
        if (!entry?.user_id) return
        const ids = entry.eventIds || [entry.id];
        await $api('/api/staff/time/approve', { method: 'POST', body: { eventIds: ids, employeeUserId: entry.user_id } })
    }

    const reject = async (entry: any, reason = "Abgelehnt") => {
        if (!entry?.user_id) return
        const ids = entry.eventIds || [entry.id];
        await $api('/api/staff/time/reject', { method: 'POST', body: { eventIds: ids, employeeUserId: entry.user_id, reason } })
    }

    const update = async (entry: any, newData: { start: string, end: string | null, type: string, description: string }) => {
        if (!entry || !entry.eventIds || entry.eventIds.length === 0) {
            throw new Error("Bearbeiten fehlgeschlagen: Keine IDs.")
        }
        await $api('/api/staff/time/edit', {
            method: 'POST',
            body: {
                originalEventIds: entry.eventIds,
                newStart: newData.start,
                newEnd: newData.end,
                newType: newData.type,
                description: newData.description,
                reason: "Manuelle Bearbeitung"
            }
        })
    }

    // 🆕 NEU: Manuellen Eintrag erstellen (Vergangenheit oder Zeitraum)
    const createEntry = async (data: { start: string, end: string | null, type: string, description: string, user_id: string }) => {
        // 1. Start Event senden
        // Wir nutzen den dynamischen Typ (work_start, vacation_start etc.)
        console.log(data)

        await $api('/api/staff/time/event', {
            method: 'POST',
            body: {
                eventtype: `${data.type}_start`,
                eventtime: data.start,
                payload: { description: data.description },
                user_id: data.user_id,
            }
        })

        // 2. End Event senden (falls vorhanden)
        if (data.end) {
            await $api('/api/staff/time/event', {
                method: 'POST',
                body: {
                    eventtype: `${data.type}_end`,
                    eventtime: data.end,
                    payload: { description: data.description },
                    user_id: data.user_id,
                }
            })
        }
    }

    return { list, start, stop, submit, approve, reject, update, createEntry }
}
