import { useTimesheetStore } from "src/stores/timesheet-store";
import { timesheetService } from "src/modules/timesheets/services/timesheet-service";

export const useTimesheetApi = () => {
    const timesheet_store = useTimesheetStore();

    const getTimesheetsByDate = async (date_string: string, employee_email?: string) => {
        timesheet_store.timesheets = [];
        timesheet_store.is_loading = true;
        const success = await timesheet_store.getPayPeriodByDateOrYearAndNumber(date_string);

        if (success) {
            await timesheet_store.getTimesheetsByOptionalEmployeeEmail(employee_email);
            timesheet_store.is_loading = false;
        }

        timesheet_store.is_loading = false;
    }

    const getTimesheetsByCurrentPayPeriod = async (employee_email?: string) => {
        if (timesheet_store.pay_period === undefined) return false;

        timesheet_store.is_loading = true;
        const success = await timesheet_store.getPayPeriodByDateOrYearAndNumber();

        if (success) {
            await timesheet_store.getTimesheetsByOptionalEmployeeEmail(employee_email);
            timesheet_store.is_loading = false;
        }

        timesheet_store.is_loading = false;
    };

    const applyPreset = async (timesheet_id: number, week_day_index?: number, date?: string, employeeEmail?: string) => {
        if (timesheet_store.timesheets.map(timesheet => timesheet.timesheet_id).includes(timesheet_id)) {
            timesheet_store.is_loading = true;
            try {
                let response;

                if (week_day_index && date)
                    response = await timesheetService.applyPresetToDay(timesheet_id, week_day_index, date, employeeEmail);
                else
                    response = await timesheetService.applyPresetToWeek(timesheet_id, employeeEmail);

                if (response.success) 
                    await timesheet_store.getTimesheetsByOptionalEmployeeEmail(employeeEmail);
            } catch (error) {
                console.error('Error applying weekly timesheet: ', error);
            }
            
            timesheet_store.is_loading = false;
        }
    }

    const getTimesheetsBySwiping = async( direction: number ) => {
        timesheet_store.is_loading = true;

        timesheet_store.getNextOrPreviousPayPeriod(direction);
        await timesheet_store.getPayPeriodByDateOrYearAndNumber();
        await timesheet_store.getTimesheetsByOptionalEmployeeEmail();
        
        timesheet_store.is_loading = false;
    }

    return {
        getTimesheetsByDate,
        getTimesheetsByCurrentPayPeriod,
        getTimesheetsBySwiping,
        applyPreset,
    };
};