import { ref } from "vue";
import { defineStore } from "pinia";
import { useTimesheetStore } from "src/stores/timesheet-store";
import { Expense } from "src/modules/timesheets/models/expense.models";
import { ExpenseService } from "src/modules/timesheets/services/expense-service";
import { date } from "quasar";

export const useExpensesStore = defineStore('expenses', () => {
    const timesheet_store = useTimesheetStore();
    const is_open = ref(false);
    const is_loading = ref(false);
    const is_hiding_create_form = ref(false);
    const mode = ref<'create' | 'update' | 'delete'>('create');
    const current_expense = ref<Expense>(new Expense(date.formatDate(new Date(), 'YYYY-MM-DD')));
    const initial_expense = ref<Expense>(new Expense(date.formatDate(new Date(), 'YYYY-MM-DD')));

    const open = (): void => {
        is_open.value = true;
        if (timesheet_store.pay_period !== undefined) {
            current_expense.value = new Expense(timesheet_store.pay_period.period_start);
            initial_expense.value = new Expense(timesheet_store.pay_period.period_start);
        }
        mode.value = 'create';
    }

    const close = () => {
        is_open.value = false;
        is_hiding_create_form.value = false;
    };

    const upsertExpense = async (expense: Expense): Promise<boolean> => {
        try {
            if (expense.id < 0) {
                const data = await ExpenseService.createExpense(expense);
                return data.success;
            }
                const data = await ExpenseService.updateExpense(expense);
                return data.success;
        } catch (err) {
            // setErrorFrom(err);
            console.error(err);
            return false;
        }
    };

    const deleteExpenseById = async (expense_id: number): Promise<boolean> => {
        const data = await ExpenseService.deleteExpenseById(expense_id);
        return data.success;
    }

    return {
        is_open,
        is_loading,
        is_hiding_create_form,
        mode,
        current_expense,
        initial_expense,
        open,
        upsertExpense,
        deleteExpenseById,
        close,
    };
});