type ScheduleOptions = {
    respect_availability: boolean
    avoid_overlaps: boolean
    fair_distribution: boolean
}

const getAuthToken = () => {
    if (typeof window !== 'undefined') {
        const token = window.localStorage.getItem('auth_token')
        if (token) {
            return token
        }
    }
    return 'placeholder-token'
}

const buildHeaders = (orgId: string) => ({
    'X-Org-Id': orgId,
    Authorization: `Bearer ${getAuthToken()}`
})

export const getAvailabilityRules = (employeeId: string, orgId: string) => {
    return $fetch(`/availability/employees/${employeeId}/rules`, {
        method: 'GET',
        headers: buildHeaders(orgId)
    })
}

export const addAvailabilityRule = (employeeId: string, payload: any, orgId: string) => {
    return $fetch(`/availability/employees/${employeeId}/rules`, {
        method: 'POST',
        headers: buildHeaders(orgId),
        body: payload
    })
}

export const deleteAvailabilityRule = (ruleId: string, orgId: string) => {
    return $fetch(`/availability/rules/${ruleId}`, {
        method: 'DELETE',
        headers: buildHeaders(orgId)
    })
}

export const getAvailabilityOverrides = (employeeId: string, from: string, to: string, orgId: string) => {
    return $fetch(`/availability/employees/${employeeId}/overrides`, {
        method: 'GET',
        headers: buildHeaders(orgId),
        query: { from, to }
    })
}

export const addAvailabilityOverride = (employeeId: string, payload: any, orgId: string) => {
    return $fetch(`/availability/employees/${employeeId}/overrides`, {
        method: 'POST',
        headers: buildHeaders(orgId),
        body: payload
    })
}

export const deleteAvailabilityOverride = (overrideId: string, orgId: string) => {
    return $fetch(`/availability/overrides/${overrideId}`, {
        method: 'DELETE',
        headers: buildHeaders(orgId)
    })
}

export const generateSchedule = (
    branchId: string,
    from: string,
    to: string,
    options: ScheduleOptions,
    apply: boolean,
    orgId: string
) => {
    return $fetch(`/scheduling/branches/${branchId}/generate`, {
        method: 'POST',
        headers: buildHeaders(orgId),
        query: { apply },
        body: { from, to, mode: 'DRAFT', options }
    })
}
