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 (date?: string) => {
        timesheet_store.is_loading = true;

        const success = await timesheet_store.getPayPeriodByDateOrYearAndNumber(date);
        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 toggleTimesheetsApprovalByEmployeeEmail = async (email: string, approval_status: boolean) => {
        timesheet_store.is_loading = true;

        const success = await timesheet_store.getTimesheetsByOptionalEmployeeEmail(email);
        if (success) {
            const approval_success = await timesheet_store.toggleTimesheetsApprovalByEmployeeEmail(email, approval_status);
            const overview = timesheet_store.pay_period_overviews.find(overview => overview.email === email);
            
            if (overview && approval_success) {
                overview.is_approved = approval_status;
                await timesheet_store.getTimesheetsByOptionalEmployeeEmail(email);
            }
        }
            
        timesheet_store.is_loading = false;
    };

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

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

        await timesheet_store.getPayPeriodReport(options);
    };

    return {
        getTimesheetOverviewsByDate,
        toggleTimesheetsApprovalByEmployeeEmail,
        getTimesheetApprovalCSVReport,
        getTimesheetOverviews,
    }
};