package ru.nbch.indicsearchservice.filter.firstlevel;

import java.util.ArrayList;
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 DefaultFirstLevelTableFilter implements FirstLevelTableFilter {
    private static final Set<String> SUPPORTED_TABLE_NAMES = Set.of(
        "RU_UID",
        "RU_APPLICATION",
        "RU_OBLIGPARTTAKE",
        "RU_BANKRUPTCY",
        "RU_SETTLED",
        "RU_OTHERLEGAL",
        "RU_CAPABILITY",
        "RU_DEBT_BURDEN_INFO",
        "ACCOUNT",
        "INFORMATION",
        "BANKRUPTCY",
        "CONSUMER_BANKRUPTCY",
        "LEGAL"
    );

    @Override
    public List<TableData> applyFilter(Map<String, List<TableData>> tableDataMapByFid, String memberCode) {
        List<TableData> result = new ArrayList<>();

        for (Map.Entry<String, List<TableData>> entry : tableDataMapByFid.entrySet()) {
            String tableName = entry.getKey();
            List<TableData> tableRows = entry.getValue();

            if (SUPPORTED_TABLE_NAMES.contains(tableName)) {
                List<TableData> tableRowsWithMatchingMemberCode = tableRows.stream()
                    .filter(row -> row.getFieldData().stream()
                        .anyMatch(field -> "MEMBER_CODE".equals(field.columnName()) &&
                            field.columnValue() != null &&
                            field.columnValue().toString().startsWith(memberCode)))
                    .toList();

                result.addAll(tableRowsWithMatchingMemberCode);
            }
        }

        return result;
    }
}
