import { normalizeObject } from "src/utils/normalize-object";
import { useExpensesStore } from "src/stores/expense-store";
import { expense_validation_schema } from "src/modules/timesheets/models/expense.validation";
import type { Expense, UpsertExpense } from "src/modules/timesheets/models/expense.models";

export const useExpensesApi = () => {
    const expenses_store = useExpensesStore();

    const toUpsertExpense = (obj: {
        old_expense?: Expense;
        new_expense?: Expense;
    }) => obj as UpsertExpense;

    const createExpenseByEmployeeEmail = async (employee_email: string, date: string): Promise<void> => {
        const upsert_expense = toUpsertExpense({ 
            new_expense: normalizeObject(expenses_store.current_expense, expense_validation_schema),
        });
        await expenses_store.upsertOrDeleteExpensesByEmployeeEmail(employee_email, date, upsert_expense);
    };

    const updateExpenseByEmployeeEmail = async (employee_email: string, date: string): Promise<void> => {
        const upsert_expense = toUpsertExpense({
            old_expense: normalizeObject(expenses_store.initial_expense, expense_validation_schema),
            new_expense: normalizeObject(expenses_store.current_expense, expense_validation_schema),
        });
        await expenses_store.upsertOrDeleteExpensesByEmployeeEmail(employee_email, date, upsert_expense);
    };

    const deleteExpenseByEmployeeEmail = async (employee_email: string, date: string): Promise<void> => {
        const upsert_expense = toUpsertExpense({
            old_expense: normalizeObject(expenses_store.initial_expense, expense_validation_schema),
        });
        await expenses_store.upsertOrDeleteExpensesByEmployeeEmail(employee_email, date, upsert_expense);
    };

    return {
        createExpenseByEmployeeEmail,
        updateExpenseByEmployeeEmail,
        deleteExpenseByEmployeeEmail,
    };
};