import { useTimesheetStore } from "src/stores/timesheet-store";
import type { TimesheetApprovalCSVReportFilters } from "src/modules/timesheet-approval/models/timesheet-approval-csv-report.models";

export const useTimesheetApprovalApi = () => {
    const timesheet_store = useTimesheetStore();
    const DATE_REGEX = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;

    const getTimesheetOverviews = async () => {
        timesheet_store.is_loading = true;

        const success = await timesheet_store.getPayPeriodByDateOrYearAndNumber();
        if (success) await timesheet_store.getTimesheetOverviews();

        timesheet_store.is_loading = false;
    }

    const getTimesheetOverviewsByDate = async (date: string) => {
        const valid_date = DATE_REGEX.test(date);
        timesheet_store.is_loading = true;

        if (valid_date) {
            const success = await timesheet_store.getPayPeriodByDateOrYearAndNumber(date);
            if (success) await timesheet_store.getTimesheetOverviews();
        }

        timesheet_store.is_loading = false;
    };

    const getTimesheetApprovalCSVReport = async (report_filter_company: boolean[], report_filter_type: boolean[], year?: number, period_number?: number) => {
        if (timesheet_store.pay_period === undefined) return;

        const [targo, solucom] = report_filter_company;
        const [shifts, expenses, holiday, vacation] = report_filter_type;
        const options = {
            types: { shifts, expenses, holiday, vacation },
            companies: { targo, solucom },
        } as TimesheetApprovalCSVReportFilters;

        await timesheet_store.getPayPeriodReportByYearAndPeriodNumber(
            year ?? timesheet_store.pay_period.pay_year,
            period_number ?? timesheet_store.pay_period.pay_period_no,
            options
        );
    };

    return {
        getTimesheetOverviewsByDate,
        getTimesheetApprovalCSVReport,
        getTimesheetOverviews,
    }
};