import type {
    AbsencesByType,
    ReportFilters,
    TasksByStatus,
    TimePerProject,
    TimePerUser,
} from './dto/reporting'
import type { AnyObject } from '~/shared/composables/useApi'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'

function buildQuery(filters: Partial<ReportFilters>, keys: (keyof ReportFilters)[]): AnyObject {
    const query: AnyObject = {}
    for (const key of keys) {
        const value = filters[key]
        if (value !== undefined && value !== null && value !== '') {
            query[key] = value
        }
    }
    return query
}

export function useReportingService() {
    const api = useApi()

    async function timePerProject(filters: ReportFilters): Promise<TimePerProject[]> {
        const query = buildQuery(filters, ['from', 'to', 'userId', 'projectId'])
        const data = await api.get<HydraCollection<TimePerProject>>('/reports/time-per-project', query, { toast: false })
        return extractHydraMembers(data)
    }

    async function timePerUser(filters: ReportFilters): Promise<TimePerUser[]> {
        const query = buildQuery(filters, ['from', 'to', 'projectId'])
        const data = await api.get<HydraCollection<TimePerUser>>('/reports/time-per-user', query, { toast: false })
        return extractHydraMembers(data)
    }

    async function tasksByStatus(filters: ReportFilters): Promise<TasksByStatus[]> {
        const query = buildQuery(filters, ['projectId'])
        const data = await api.get<HydraCollection<TasksByStatus>>('/reports/tasks-by-status', query, { toast: false })
        return extractHydraMembers(data)
    }

    async function absencesByType(filters: ReportFilters): Promise<AbsencesByType[]> {
        const query = buildQuery(filters, ['from', 'to', 'userId'])
        const data = await api.get<HydraCollection<AbsencesByType>>('/reports/absences-by-type', query, { toast: false })
        return extractHydraMembers(data)
    }

    return { timePerProject, timePerUser, tasksByStatus, absencesByType }
}
