import { ref } from "vue";
import { defineStore } from "pinia";
import { unwrapAndClone } from "src/utils/unwrap-and-clone";
import { timesheetService } from "src/modules/timesheets/services/timesheet-service";
import { useTimesheetStore } from "src/stores/timesheet-store";
import { default_shift, type UpsertAction, type Shift, type UpsertShift } from "src/modules/timesheets/models/shift.models";

export const useShiftStore = defineStore('shift', () => {
    const is_open = ref(false);
    const mode = ref<UpsertAction>('create');
    const date_iso = ref<string>('');
    const current_shift = ref<Shift>(default_shift);
    const initial_shift = ref<Shift>(default_shift);

    const timesheet_store = useTimesheetStore();

    const open = (next_mode: UpsertAction, date: string, current: Shift, initial: Shift) => {
        mode.value = next_mode;
        date_iso.value = date;
        current_shift.value = current;                    // new shift
        initial_shift.value = initial;                    // old shift
        is_open.value = true;
    };

    const openCreate = (date: string) => {
        open('create', date, default_shift, default_shift);
    };

    const openUpdate = (date: string, shift: Shift) => {
        open('update', date, shift, unwrapAndClone(shift));
    };

    const openDelete = (date: string, shift: Shift) => {
        open('delete', date, default_shift, shift);
    }

    const close = () => {
        is_open.value = false;
        mode.value = 'create';
        date_iso.value = '';
        current_shift.value = default_shift;
        initial_shift.value = default_shift;
    };

    const upsertOrDeleteShiftByEmployeeEmail = async (employee_email: string, upsert_shift: UpsertShift) => {
        const encoded_email = encodeURIComponent(employee_email);
        const encoded_date = encodeURIComponent(current_shift.value.date);

        try {
            const result = await timesheetService.upsertOrDeleteShiftsByDateAndEmployeeEmail(encoded_email, [ upsert_shift, ], encoded_date);
            timesheet_store.pay_period_details = result;
        } catch (err) {
            console.log('error doing thing: ', err)
            // const status_code: number = err?.response?.status ?? 500;
            // const data = err?.response?.data ?? {};
            // throw new GenericApiError({
            //     status_code,
            //     error_code: data.error_code,
            //     message: data.message || data.error || err.message,
            //     context: data.context,
            // });
        } finally {
            close();
        }
    }


    return {
        is_open,
        mode,
        date_iso,
        current_shift,
        initial_shift,
        openCreate,
        openUpdate,
        openDelete,
        close,
        upsertOrDeleteShiftByEmployeeEmail,
    };
})