import API from '@/api/api.js';
import APIFile from '@/api/apiFile.js';

export class AuthService {
    async login(payload) {
        const config = {
            method: 'POST',
            url: '/auth/sign-in',
            data: payload,
        };
        return await API.request(config);
    }

    logout() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/auth/sign-out',
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return API.request(config);
    }

    async register(payload) {
        const token = localStorage.getItem('accessToken');

        if (!token) {
            // администратор не авторизован → лучше сразу показать ошибку
            throw new Error('Необходима авторизация для создания пользователей');
        }

        const config = {
            method: 'POST',
            url: '/auth/register',
            data: payload,
            headers: {Authorization: `Bearer ${token}`},
        };
        return await API.request(config);
    }

    async changePassword(payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'PATCH',
            url: '/user/change-password',
            data: payload,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getUsers() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: '/users',
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getUserInfo(id) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: `/users/${id}`,
            headers: {Authorization: `Bearer ${token}`}
        })
    }

    async changeUserInfo(id, payload) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'PATCH',
            url: `/users/${id}`,           // патчим по тому же адресу
            data: payload,
            headers: {Authorization: `Bearer ${token}`}
        })
    }

    async deleteUser(userId) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'DELETE',
            url: `/users/${userId}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    /**
     * Получить список логов с поддержкой query-параметров (например ?page=2)
     *
     * @param {Object} query — объекты вида { page: 2, per_page: 50, ... }
     * @returns {Promise}
     */
    async getLogs(query = {}) {
        // берём токен
        const token = localStorage.getItem('accessToken');
        // собираем строку параметров
        const params = new URLSearchParams(query).toString();
        // делаем запрос
        return API.request({
            method: 'GET',
            url: `/logs${params ? `?${params}` : ''}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        });
    }

    async getPointForMap(districtId = null) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: '/point-list-for-map',
            timeout: 300000,
            headers: {Authorization: `Bearer ${token}`},
            // если передан districtId — кладём его в params
            params: districtId != null ? {district_id: districtId} : {}
        };
        return API.request(config);
    }

    async getPointList() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: '/point-list',
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getPointInfo(pointId) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/point/${pointId}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getPointInfoForEdit(id) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/get-point-info/${id}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async savePointPlan(payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/sen-manager/create-point-plan',
            data: payload,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getSchedulDraftInfo(id) {
        console.log(id);

        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/get-draft-schedule/${id}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async createSignature(id) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: `/create_signature_schedule/${id}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getSchedulesInfo(id) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/get-schedules/${id}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async saveOperatorPoint(payload, point_id = null) {
        const token = localStorage.getItem('accessToken');
        const method = point_id ? 'POST' : 'PATCH';
        const config = {
            method: method,
            url: '/create-operator-point',
            data: payload,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getRegionsAndSeniorManagers() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: '/get-regions-and-sen-managers',
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async purposeSenManager(payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/purpose-sen-manager',
            data: payload,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getRegionsAndManagers(id) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/get-districts-and-managers/${id}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async purposeManager(payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/purpose-manager',
            data: payload,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getPointsAndOperators() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/get-points-and-operators`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async proposeOperatorToPoint(payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/purpose-operator',
            data: payload,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getPoints() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: '/point-list',
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getPointNames() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: '/points/names',
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async createPoint(formData) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/create-point',
            data: formData,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async infoForCreatePoint() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: '/create-point',
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getSchedulePlanList() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/sen-manager/schedule-plan-list`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async creteSchadulPlan(payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/create-schedule-plan',
            data: payload,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async schedulePlanInfo(id) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/sen-manager/create-point-plan/${id}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getPointPlanList() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/sen-manager/point-plans-list`,
            timeout: 300000,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async getPointPlanInfo(id) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/sen-manager/point-plan/${id}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async updatePointPlan(id, payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'PATCH',
            url: `/sen-manager/point-plan/${id}`,
            data: payload,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    /**
     * @param {Object} params — { page, per_page, request_id, district_id, subgroup_manager_id, month }
     */
    async getPointsOperator({
                                page,
                                per_page,
                                request_id,
                                district_id,
                                subgroup_manager_id,
                                month
                            } = {}) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'GET',
            url: '/operator/points-plans',
            headers: {Authorization: `Bearer ${token}`},
            params: {
                ...(page != null && {page}),
                ...(per_page != null && {per_page}),
                ...(request_id != null && {request_id}),
                ...(district_id != null && {district_id}),
                ...(subgroup_manager_id != null && {subgroup_manager_id}),
                ...(month != null && {month}),
            },
        });
    }

    async uploadPhoto(payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/upload-photo',
            data: payload,
            headers: {
                Authorization: `Bearer ${token}`,
                'Content-Type': 'multipart/form-data',
            },
        };
        return await API.request(config);
    }

    async deletePointPlan(id) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'DELETE',
            url: `/sen-manager/point-plan/${id}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async editPoint(formData) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/edit-point',
            data: formData,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await APIFile.request(config);
    }

    async getNotifications() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: '/notifications',
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async markNotificationAsRead(notificationId) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: `/notifications/${notificationId}/read`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    /**
     * Генерирует план работ на интервал дат,
     * пропуская выходные и праздники.
     *
     * @param {{ start_date: string, end_date: string, point_ids?: number[] }} payload
     */
    async generatePointPlans(payload) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'POST',
            url: '/generate-point-plans',
            data: payload,
            timeout: 300_000,
            headers: {Authorization: `Bearer ${token}`},
        });
    }

    async signaturePointPlan(id) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: `/signature-pont-plan/${id}`,
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    async uploadFile(payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/upload-file', // Убедись, что маршрут называется правильно на бэкенде
            data: payload,
            headers: {
                Authorization: `Bearer ${token}`,
                'Content-Type': 'multipart/form-data',
            },
        };
        return await API.request(config);
    }

    /**
     * Получить список заявок
     * GET /api/requests
     */
    async getRequests() {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: '/requests',
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        return await API.request(config);
    }

    /**
     * 2) Назначить менеджера группы (group_manager) на регион
     *    payload = { region_id, group_manager_id }
     */
    async assignGroupManager(payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/regions/assign-group-manager',
            data: payload,
            headers: {Authorization: `Bearer ${token}`},
        };
        return API.request(config);
    }

    /**
     * 4) Назначить менеджера подгруппы (subgroup_manager) на район
     *    payload = { district_id, subgroup_manager_id }
     */
    async assignSubgroupManager(payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/districts/assign-subgroup-manager',
            data: payload,
            headers: {Authorization: `Bearer ${token}`},
        };
        return API.request(config);
    }

    // 1) Регионы + групповые менеджеры
    async getRegionsAndGroupManagers() {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'GET',
            url: '/regions/group-managers',
            headers: {Authorization: `Bearer ${token}`},
        });
    }


    async getDistrictsForGroupAssignment() {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'GET',
            url: '/ref/districts/group-assignment',
            headers: {Authorization: `Bearer ${token}`},
        });
    }

    // 3) Районы + кандидаты в менеджеры подгрупп
    async getDistrictsAndSubgroupManagers() {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'GET',
            url: '/districts/subgroup-managers',
            headers: {Authorization: `Bearer ${token}`},
        });
    }

    /**
     * 2) Назначить менеджера группы (group_manager) на район
     *    payload = { district_id, group_manager_id }
     */
    async assignGroupManagerToDistrict(payload) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'POST',
            url: '/districts/assign-group-manager',
            data: payload,
            headers: {Authorization: `Bearer ${token}`},
        };
        return API.request(config);
    }

    async getSchedulePlanMeta(planId) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'GET',
            url: `/schedule-plan/${planId}/meta`,
            headers: {Authorization: `Bearer ${token}`},
        });
    }

    async getCalendarView(id, query = {}) {
        const token = localStorage.getItem('accessToken')
        const params = new URLSearchParams(query).toString()
        return API.request({
            method: 'GET',
            url: `/sen-manager/calendar/view/${id}${params ? `?${params}` : ''}`,
            headers: {Authorization: `Bearer ${token}`}
        })
    }

    /**
     * POST /api/requests/{request_id}/plan-signature
     * body: { month: number, year: number }
     */
    async signPlan({request_id, month, year}) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'POST',
            url: `/requests/${request_id}/plan-signature`,
            headers: {Authorization: `Bearer ${token}`},
            data: {month, year},
        });
    }

    async getCounters() {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'GET',
            url: '/counters',
            headers: {Authorization: `Bearer ${token}`}
        });
    }

    // POST /api/counters
    async createCounter(payload) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'POST',
            url: '/counters',
            data: payload,
            headers: {Authorization: `Bearer ${token}`},
        });
    }

    // PUT /api/counters/{id}
    async updateCounter(id, payload) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'PUT',
            url: `/counters/${id}`,
            data: payload,
            headers: {Authorization: `Bearer ${token}`},
        });
    }

    // DELETE /api/counters/{id}
    async deleteCounter(id) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'DELETE',
            url: `/counters/${id}`,
            headers: {Authorization: `Bearer ${token}`},
        });
    }

    /**
     * Получить подписанные месяцы по заявке
     * GET /sen-manager/calendar/view/${requestId}/signed-periods
     */
    async getSignedPeriods(requestId) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'GET',
            url: `/sen-manager/calendar/view/${requestId}/signed-periods`,
            headers: {Authorization: `Bearer ${token}`},
        });
    }

    // 1) Забрать список категорий ТС
    async getVehicleCategories() {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: '/vehicle-categories',
            headers: {Authorization: `Bearer ${token}`}
        })
    }

    // 2) Забрать уже сохранённые часы/количества для плана
    async getPlanStats(planId) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: `/plan-stats/${planId}`,
            headers: {Authorization: `Bearer ${token}`}
        })
    }

    // 3) Сохранить часы/количества
    async savePlanStats(planId, payload) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'POST',
            url: `/plan-stats/${planId}`,
            data: payload,
            headers: {
                Authorization: `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        })
    }

    // 4) Загрузка файлов (фото ДО/ПОСЛЕ и документы)
    async uploadPlanFile(formData) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'POST',
            url: '/plan-files/upload',
            timeout: 300000,
            data: formData,
            headers: {
                Authorization: `Bearer ${token}`,
                'Content-Type': 'multipart/form-data'
            }
        })
    }

    // 5) Список загруженных файлов
    async listPlanFiles(planId) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: `/plan-files/${planId}`,
            headers: {Authorization: `Bearer ${token}`}
        })
    }

    async deletePlanFile(id) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'DELETE',
            url: `/plan-files/${id}`,
            headers: {Authorization: `Bearer ${token}`}
        });
    }

    /** Получить расчёт в JSON */
    async getTrafficReport(params) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'GET',
            url: '/reports/traffic',
            params,
            headers: {Authorization: `Bearer ${token}`},
        });
    }

    /** Скачиваем Excel */
    async exportTrafficReport(params) {
        const token = localStorage.getItem('accessToken');
        const response = await API.request({
            method: 'GET',
            url: 'reports/traffic/detailed',
            timeout: 300000,
            params,
            headers: {Authorization: `Bearer ${token}`},
            responseType: 'blob',
        });
        // сохраняем файл
        const blob = new Blob([response.data], {type: response.headers['content-type']});
        const cd = response.headers['content-disposition'] || '';
        const filename = cd.match(/filename="?([^"]+)"?/)?.[1] || 'traffic_report.xlsx';
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        link.remove();
    }

    /** JSON‑версия 24‑колоночного отчёта */
    async getTrafficDetailedReport(params) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: '/reports/traffic/detailed',
            params,
            headers: {Authorization: `Bearer ${token}`},
        })
    }

    /** Excel‑выгрузка 24‑колоночного отчёта */
    async exportTrafficDetailedReport(params, districtName = null) {
        const token = localStorage.getItem('accessToken')
        // делаем запрос
        const res = await API.request({
            method: 'GET',
            url: '/reports/traffic/detailed/export',
            timeout: 300000,
            params,
            responseType: 'blob',
            headers: {Authorization: `Bearer ${token}`},
        })

        // создаём Blob из ответа
        const blob = new Blob([res.data], {type: res.headers['content-type']})

        // подставляем название района или дефолт
        const name = districtName ?? 'Оренбургская область'
        const filename = `РасчетИнтенсивности_${name}.xlsx`

        // скачиваем
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = filename
        document.body.appendChild(a)
        a.click()
        a.remove()
        URL.revokeObjectURL(url)
    }

    async exportScheduleExcel(id, {month, district, freq, request_id}) {
        const params = new URLSearchParams({month, district, freq, request_id}).toString();
        const res = await API.request({
            method: 'GET',
            url: `/reports/schedules/${id}/export-excel?${params}`,
            headers: {
                Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
                Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            },
            responseType: 'blob',       // ← важно!
            timeout: 300000
        });

        const blob = res.data;       // это уже Blob
        const cd = res.headers['content-disposition'] || '';
        const filename = cd.match(/filename="?([^"]+)"?/)?.[1] || 'schedule.xlsx';

        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        link.remove();
    }

    async getPlanSummary(point_id, request_id, schedule_id) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: 'point-plans/summary',
            params: {point_id, request_id, schedule_id},
            headers: {Authorization: `Bearer ${token}`},
        })
    }

    /** GET /api/ref/managers?level={group|subgroup} */
    async getRefManagers(level) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: '/ref/managers',
            params: {level},
            headers: {Authorization: `Bearer ${token}`},
        })
    }

    /** GET /api/ref/districts */
    async getRefDistricts() {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: '/ref/districts',
            headers: {Authorization: `Bearer ${token}`},
        })
    }

    /** GET  /api/regions */
    async getRegions() {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: '/regions',
            headers: {Authorization: `Bearer ${token}`},
        })
    }

    /** GET  /api/points/{id} */
    async getPoint(id) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: `/points/${id}`,
            headers: {Authorization: `Bearer ${token}`},
        })
    }

    /** POST /api/points/{id}  (FormData + _method=PATCH) */
    async updatePoint(id, formData) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'POST',
            url: `/points/${id}`,
            data: formData,
            headers: {
                Authorization: `Bearer ${token}`,
                'Content-Type': 'multipart/form-data',
            },
        })
    }

    /** GET /api/logs/objects */
    async getLogObjects() {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'GET',
            url: '/logs/objects',
            headers: {Authorization: `Bearer ${token}`},
        });
    }

    /** POST /api/requests */
    async createRequest(payloads) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'POST',
            url: '/requests',
            data: payloads,
            headers: {Authorization: `Bearer ${token}`},
        })
    }

    /** POST /api/requests/{id}/points */
    async addPointsToRequest(id, pointIds) {
        console.log(id)
        console.log(pointIds)
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'POST',
            url: `/requests/${id}/add-points`,
            data: {point_ids: pointIds},
            headers: {Authorization: `Bearer ${token}`},
        })
    }

    async getPointsByRequest(id) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: `/requests/${id}/points`,
            headers: {Authorization: `Bearer ${token}`},
        })
    }

    async changeRequest(id, payload) {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'PATCH',
            url: `/requests/${id}`,
            data: payload,               // payload = { name, description, point_ids: [...] }
            headers: {Authorization: `Bearer ${token}`},
        })
    }

    /**
     * Скачать заполненный шаблон КС-2
     * GET /api/reports/schedule/download
     * @param {{ request_id: number, district_id: number, season: number }} params
     * @param districtName
     */
    async downloadKc2Template(params, districtName) {
        const token = localStorage.getItem('accessToken');

        const response = await API.request({
            method: 'GET',
            url: '/reports/ks2/download',
            params,
            headers: {
                Authorization: `Bearer ${token}`,
                Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            },
            responseType: 'blob'
        });

        const filename = `АКТ КС-2_${districtName}.xlsx`;

        // 2) скачиваем blob
        const blob = new Blob([response.data], {type: response.headers['content-type']});
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        a.remove();
        URL.revokeObjectURL(url);
    }

    /**
     * GET /api/requests/{id}/photos
     * @param {number} id
     * @param {number|null} districtId
     * @param {number} sheets
     */
    async getRequestPhotos(id, districtId = null, sheets = 1) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'GET',
            url: `/requests/${id}/photos`,
            params: {district_id: districtId, sheets},
            headers: {Authorization: `Bearer ${token}`},
        });
    }

    /**
     * Загрузить файл и получить сопоставление по именам:
     * вернёт { matched_point_ids: [], not_found_names: [] }
     */
    importPointsByName(requestId, file) {
        const formData = new FormData();
        const token = localStorage.getItem('accessToken');
        formData.append('file', file);
        return API.request({
            method: 'POST',
            url: `/requests/${requestId}/import-by-name`,
            data: formData,
            headers: {Authorization: `Bearer ${token}`, 'Content-Type': 'multipart/form-data'},
        });
    }

    /**
     * Передать список найденных ID и синхронизировать (деактивировать старые работы)
     * Ожидает body: { point_ids: [1,2,3,...] }
     */
    async syncPoints(requestId, pointIds) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'POST',
            url: `/requests/${requestId}/sync-points`,
            headers: {Authorization: `Bearer ${token}`},
            data: {point_ids: pointIds},
        });
    }

    // POST /api/requests/{id}/lock
    async lockRequest(requestId) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'POST',
            url: `/requests/${requestId}/lock`,
            headers: {Authorization: `Bearer ${token}`}
        });
    }

    async getPreviousStats(point_id, year, month) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: '/plan-stats/previous',
            headers: {Authorization: `Bearer ${token}`},
            params: {point_id, year, month},
        };
        return await API.request(config);
    }

    async getRequestDateRange(requestId) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/requests/${requestId}/date-range`,
            headers: {Authorization: `Bearer ${token}`},
        };
        return await API.request(config);
    }
    async getRequestDistrictRanges(requestId) {
        const token = localStorage.getItem('accessToken');
        const config = {
            method: 'GET',
            url: `/requests/${requestId}/district-date-ranges`,
            headers: { Authorization: `Bearer ${token}` },
        };
        return await API.request(config);
    }

    async startPhotoReport(requestId, districtId = null) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'POST',
            url: `/reports/photos`,
            headers: { Authorization: `Bearer ${token}` },
            data: { request_id: requestId, district_id: districtId },
        });
    }

// GET /api/reports/photos/status/{job_id}
    async getPhotoReportStatus(jobId) {
        const token = localStorage.getItem('accessToken');
        return API.request({
            method: 'GET',
            url: `/reports/photos/status/${jobId}`,
            headers: { Authorization: `Bearer ${token}` },
        });
    }

    /**
     * GET /api/reports/photos
     */
    async listPhotoReports() {
        const token = localStorage.getItem('accessToken')
        return API.request({
            method: 'GET',
            url: '/reports/photos',
            headers: { Authorization: `Bearer ${token}` },
        })
    }
}

export const authService = new AuthService();
