// File: src/resources/financial.js

/**
 * لود داده‌های مالی پروژه:
 *  - financial_items
 *  - task_costs
 *  - cashflow
 * @param {Object} state
 * @param {Object} projectData
 */
export function loadFinancialData(state, projectData) {
    loadFinancialItems(state, projectData);
    loadTaskCosts(state, projectData);
    loadCashflow(state, projectData);
}

function loadFinancialItems(state, projectData) {
    if (!Array.isArray(projectData.financial_items)) {
        state.financialItems.byId = {};
        state.financialItems.byCategory = {};
        return;
    }

    state.financialItems.byId = {};
    state.financialItems.byCategory = {};

    projectData.financial_items.forEach(item => {
        const id = item.id;
        if (!id) return;

        const category = item.category ?? 'general';

        const fi = {
            id,
            category,
            code: item.code ?? '',
            name: item.name ?? '',
            description: item.description ?? '',
            amount: item.amount ?? 0,
            currency: item.currency ?? state.project.currency,
            date: item.date ?? null,
            taskId: item.task_id ?? null,
            wbsId: item.wbs_id ?? null
        };

        state.financialItems.byId[id] = fi;

        if (!state.financialItems.byCategory[category]) {
            state.financialItems.byCategory[category] = [];
        }
        state.financialItems.byCategory[category].push(id);
    });
}

function loadTaskCosts(state, projectData) {
    if (!Array.isArray(projectData.task_costs)) {
        state.costs.taskCosts = { byTaskId: {} };
        return;
    }

    state.costs.taskCosts = { byTaskId: {} };

    projectData.task_costs.forEach(tc => {
        const taskId = tc.task_id;
        if (!taskId) return;

        const entry = {
            taskId,
            directCost: tc.direct_cost ?? 0,
            indirectCost: tc.indirect_cost ?? 0,
            totalCost: tc.total_cost ?? null,
            currency: tc.currency ?? state.project.currency
        };

        state.costs.taskCosts.byTaskId[taskId] = entry;
    });
}

function loadCashflow(state, projectData) {
    if (!Array.isArray(projectData.cashflow)) {
        state.cashflow.byDate = {};
        return;
    }

    state.cashflow.byDate = {};

    projectData.cashflow.forEach(cf => {
        const date = cf.date;
        if (!date) return;

        state.cashflow.byDate[date] = {
            date,
            inflow: cf.inflow ?? 0,
            outflow: cf.outflow ?? 0,
            net: cf.net ?? ((cf.inflow ?? 0) - (cf.outflow ?? 0)),
            currency: cf.currency ?? state.project.currency
        };
    });
}
