import apiClient from '@/services/axiosSetup';
import {Budget, BudgetCategory} from "@/models/Budget";
import {format} from "date-fns";
// Импортируете настроенный экземпляр axios

export const getBudgetInfos = async () => {
    try {
        let spaceId = localStorage.getItem("spaceId")
    let response = await apiClient.get(`/spaces/${spaceId}/budgets`);
    let budgetInfos = response.data;
    budgetInfos.forEach((budgetInfo: Budget) => {
        budgetInfo.dateFrom = new Date(budgetInfo.dateFrom);
        budgetInfo.dateTo = new Date(budgetInfo.dateTo);
        budgetInfo.plannedExpenses?.forEach(e => {
            e.date = new Date(e.date)
        })

        budgetInfo.plannedIncomes?.forEach(e => {
            e.date = new Date(e.date)
        })

        budgetInfo.transactions?.forEach(e => {
            e.date = new Date(e.date)
        })
    })
    return budgetInfos
    } catch (e) {
        console.log(e)
        throw e

    }
}

export const getBudgetTransactions = async (budgetId, transactionType, categoryType) => {

    let url = `/budgets/${budgetId}/transactions`
    if (transactionType && !categoryType) {
        url += '?type=' + transactionType
    }
    if (transactionType && categoryType) {
        url += '/' + transactionType + '/' + categoryType
    }
    // if (!categoryType) {
    //     throw new Error('No CategoryType');
    // }
    let response = await apiClient.get(url);
    let transactions = response.data;
    transactions.forEach(e => {
        e.date = new Date(e.date)
    })
    return transactions
}

export const getBudgetCategories = async (budgetId) => {
    let response = await apiClient.get('/budgets/' + budgetId + '/categories/');
    return response.data;
}

export const getBudgetCategoriesSums = async (budgetId) => {
    let response = await apiClient.get('/budgets/' + budgetId + '/categories/_calc_sums');
    return response.data;
}

export const getBudgetInfo = async (budget_id: string) => {

    let budgetInfo = await apiClient.get('/budgets/' + budget_id);
    budgetInfo = budgetInfo.data;

    budgetInfo.dateFrom = new Date(budgetInfo.dateFrom)
    budgetInfo.dateTo = new Date(budgetInfo.dateTo)
    return budgetInfo

};


export const getWarns = async (budgetId: string, hidden: Boolean = null) => {
    let url = `/budgets/${budgetId}/warns`
    if (hidden) {
        url += `?hidden=${hidden}`
    }
    let warns = await apiClient.get(url);
    return warns.data
}

export const hideWarnRequest = async (budgetId: string, warnId: string) => {
    await apiClient.post(`/budgets/${budgetId}/warns/${warnId}/hide`);
}

export const updateBudgetCategoryRequest = async (budget_id, category: BudgetCategory) => {
    return await apiClient.post('/budgets/' + budget_id + '/categories/' + category.category.id + "/limit", {"limit": category.currentLimit}).then(i => i.data);
}

export const createBudget = async (budget: Budget, createRecurrent: Boolean) => {

   try {
        let spaceId = localStorage.getItem("spaceId")
       let budgetToCreate = JSON.parse(JSON.stringify(budget));
       budgetToCreate.dateFrom = format(budget.dateFrom, 'yyyy-MM-dd')
       budgetToCreate.dateTo = format(budget.dateTo, 'yyyy-MM-dd')
       let data = {
           budget: budgetToCreate,
           createRecurrent: createRecurrent
       }
       await apiClient.post(`/spaces/${spaceId}/budgets`, data);

   } catch (e){
       console.error(e)
       throw e
   }
}


export const deleteBudgetRequest = async (budgetId: string) => {
    try {
        // throw Error("test")
        let response = await apiClient.delete(`/budgets/${budgetId}`);
    } catch (error) {
        console.log(error);
        throw error;
    }
}