import { useAuthStore } from "src/stores/auth-store";
import { useTimesheetStore } from "src/stores/timesheet-store"

export const useTimesheetApi = () => {
    const timesheet_store = useTimesheetStore();
    const auth_store = useAuthStore();
    const NEXT = 1;
    const PREVIOUS = -1;

    const getPayPeriodDetailsByDate = async (date_string: string, employee_email?: string) => {
        const success = await timesheet_store.getPayPeriodByDateOrYearAndNumber(date_string);

        if (success) {
            await timesheet_store.getPayPeriodDetailsByEmployeeEmail(employee_email ?? auth_store.user.email)
        }
    }

    const getNextOrPreviousPayPeriodDetails = async (direction: number, employee_email?: string) => {
        const { pay_period } = timesheet_store;
        let new_number = pay_period.pay_period_no + direction;
        let new_year = pay_period.pay_year;

        if (new_number > 26) {
            new_number = 1;
            new_year += 1;
        }

        if (new_number < 1) {
            new_number = 26;
            new_year -= 1;
        }

        const success = await timesheet_store.getPayPeriodByDateOrYearAndNumber(new_year, new_number);

        if (success) {
            await timesheet_store.getPayPeriodDetailsByEmployeeEmail(employee_email ?? auth_store.user.email);
        }
    };

    const getNextPayPeriodDetails = async (employee_email?: string) => {
        await getNextOrPreviousPayPeriodDetails(NEXT, employee_email ?? auth_store.user.email);
    }
    
    const getPreviousPayPeriodDetails = async (employee_email?: string) => {
        await getNextOrPreviousPayPeriodDetails(PREVIOUS, employee_email ?? auth_store.user.email);
    }

    return {
        getPayPeriodDetailsByDate,
        getNextPayPeriodDetails,
        getPreviousPayPeriodDetails,
    };
};