package ru.nbch.indicsearchservice.filter.secondlevel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.stereotype.Component;
import ru.nbch.indicsearchservice.model.TableData;

@Component
public class RuUidSecondLevelTableFilter implements SecondLevelTableFilter {
    private static final Set<String> SUPPORTED_TABLE_NAMES = Set.of(
        "RU_ACCOUNT_AMT",
        "RU_AMENDMENT",
        "RU_ARREAR",
        "RU_COBORROWER",
        "RU_DUEARREAR",
        "RU_FUNDDATE",
        "RU_MONTHAVERPAYMT",
        "RU_OVERALLVAL",
        "RU_PASTDUEARREAR",
        "RU_PAYMT",
        "RU_PAYMT_CONDITION",
        "RU_SOURCENONMONETOBLIG",
        "RU_TRADE"
    );

    @Override
    public void applyFilter(List<TableData> firstLevelTableDataList, Map<String, List<TableData>> tableDataMapByFid) {
        if (firstLevelTableDataList == null || firstLevelTableDataList.isEmpty() || tableDataMapByFid == null) {
            return;
        }

        Map<Object, List<TableData>> relatedTablesByAccSerialNum = new HashMap<>();

        for (String supportedTableName : SUPPORTED_TABLE_NAMES) {
            List<TableData> childTables = tableDataMapByFid.get(supportedTableName);

            if (childTables != null) {
                for (TableData childTable : childTables) {
                    Object accSerialNum = getFieldValue(childTable, "ACC_SERIAL_NUM");
                    if (accSerialNum != null) {
                        relatedTablesByAccSerialNum
                            .computeIfAbsent(accSerialNum, k -> new ArrayList<>())
                            .add(childTable);
                    }
                }
            }
        }

        for (TableData parentTable : firstLevelTableDataList) {
            Object serialNum = getFieldValue(parentTable, "SERIAL_NUM");

            if (serialNum != null) {
                List<TableData> matchedParentTables = relatedTablesByAccSerialNum.get(serialNum);
                if (matchedParentTables != null) {
                    parentTable.getRelatedTableData().addAll(matchedParentTables);
                }
            }
        }
    }

    private Object getFieldValue(TableData tableData, String targetColumnName) {
        if (tableData.getFieldData() == null) {
            return null;
        }

        for (TableData.FieldData field : tableData.getFieldData()) {
            if (targetColumnName.equals(field.columnName())) {
                return field.columnValue();
            }
        }

        return null;
    }
}
