import { ref } from "vue";
import { defineStore } from "pinia";
import { EmployeeListService } from "src/modules/employee-list/services/employee-list-service";
import { EmployeeProfile } from "src/modules/employee-list/models/employee-profile.models";

export const useEmployeeStore = defineStore('employee', () => {
    const employee = ref<EmployeeProfile>(new EmployeeProfile);
    const employee_list = ref<EmployeeProfile[]>([]);
    const is_add_modify_dialog_open = ref<boolean>(false);
    const management_mode = ref<'modify_employee' | 'add_employee'>('add_employee');
    const is_loading = ref(false);

    const openAddModifyDialog = async (employee_email?: string) =>{
        is_add_modify_dialog_open.value = true;

        if (employee_email === undefined) {
            management_mode.value = 'add_employee'
            employee.value = new EmployeeProfile();
            return;
        }

        is_loading.value = true;
        management_mode.value = 'modify_employee';
        await getEmployeeDetails(employee_email);
        is_loading.value = false;
    }

    const getEmployeeList = async () => {
        is_loading.value = true;
        try {
            const response = await EmployeeListService.getEmployeeList();
            employee_list.value = response;
        } catch (error) {
            console.error("Ran into an error fetching employee list: ", error);
            //TODO: trigger an alert window with an error message here!
        }
        is_loading.value = false;
    };

    const getEmployeeDetails = async (email?: string) => {
        is_loading.value = true;
        try {
            if (email === undefined) {
                const response = await EmployeeListService.getEmployeeDetails();
                employee.value = response;
            } else{
                const response = await EmployeeListService.getEmployeeDetailsWithEmployeeEmail(email);
                employee.value = response;
            }

        } catch (error) {
            console.error('There was an error retrieving employee info: ', error);
            //TODO: trigger an alert window with an error message here!
        }
        is_loading.value = false;
    };

    return { 
        employee, 
        employee_list, 
        is_add_modify_dialog_open,
        management_mode,
        is_loading, 
        getEmployeeList, 
        getEmployeeDetails,
        openAddModifyDialog, 
    };
});

