/* 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";

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

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

    const createNewShifts = async (employee_email?: string | undefined): Promise<boolean> => {
        if (timesheet_store.timesheets === undefined) return 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, employee_email);
                if (response.success) {
                    return true;
                }
                else { shift_errors.value.push(response.error!) }
            }
            return false;
        } catch (error) {
            Notify.create('Error creating new shifts');
            return false;
        }
    };

    const updateShifts = async (employee_email?: string | undefined): 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, employee_email);

                if (response.success) {
                    return true;
                }
            }
            
            return false;
        } catch (error) {
            Notify.create('Error updating shifts');
            return false;
        }
    }

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