/* eslint-disable */
import { ref } from "vue";
import { Notify } from "quasar";
import { defineStore } from "pinia";
import { ShiftService } from "src/modules/timesheets/services/shift-service";
import { useTimesheetStore } from "src/stores/timesheet-store";
import type { ShiftAPIError } from "src/modules/timesheets/models/shift.models";

export const useShiftStore = defineStore('shift_store', () => {
    const timesheet_store = useTimesheetStore();
    const shift_errors = ref<ShiftAPIError[]>([]);

    const deleteShiftById = async (shift_id: number): Promise<boolean> => {
        try {
            await ShiftService.deleteShiftById(shift_id);
            return true;
        } catch (error) {
            console.error('DEV ERROR || error while deleting shift: ', error);
            return false;
        }
    };

    const createNewShifts = async (): Promise<boolean> => {
        if (timesheet_store.timesheets === undefined) return false;
        const has_errors = false;

        try {
            const days = timesheet_store.timesheets.flatMap(week => week.days);
            const new_shifts = days.flatMap(day => day.shifts).filter(shift => shift.id < 0);

            if (new_shifts?.length > 0) {
                const response = await ShiftService.createNewShifts(new_shifts);
                if (response.every(res => res.ok)) {
                    return true;
                }
                else {
                    response.forEach(res => {
                        shift_errors.value.push(res.error!);
                    });
                }
            }
            return false;
        } catch (error) {
            Notify.create('Error creating new shifts');
            return false;
        }
    };

    const updateShifts = async (): Promise<boolean> => {
        if (timesheet_store.timesheets === undefined) return false;

        try {
            const existing_shifts = timesheet_store.timesheets.flatMap(week => week.days).flatMap(day => day.shifts).filter(shift => shift.id > 0);

            if (existing_shifts?.length > 0) {
                const response = await ShiftService.updateShifts(existing_shifts);

                if (response.status < 400) {
                    return true;
                }
            }

            Notify.create('No shifts to update')
            return false;
        } catch (error) {
            Notify.create('Error updating shifts');
            return false;
        }
    }

    return {
        shift_errors,
        deleteShiftById,
        createNewShifts,
        updateShifts,
    }
})