package com.kbs.kbsintranett;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UserFilterHelper {

    private static final List<Integer> EXCLUDED_IDS = Arrays.asList(50, 51); // felles@kbs.no og kbs@kbs.no
    private static final String REQUIRED_DOMAIN = "@kbs.no";

    public static List<User> getFilteredUsers(List<User> allUsers) {
        if (allUsers == null) return new ArrayList<>();

        UserManager me = UserManager.getInstance();
        String myEmail = me.getUserEmail();

        List<User> sanitizedList = new ArrayList<>();
        for (User u : allUsers) {
            String email = u.getEmail() != null ? u.getEmail().toLowerCase() : "";
            if (!email.endsWith(REQUIRED_DOMAIN)) continue;
            if (EXCLUDED_IDS.contains(u.getId())) continue;
            if (u.getRoles() == null || u.getRoles().isEmpty()) continue;

            sanitizedList.add(u);
        }

        if (me.isEditorOrAbove()) {
            return sanitizedList;
        }

        List<User> finalResult = new ArrayList<>();
        List<String> myRoles = getRolesForEmail(sanitizedList, myEmail);

        // NY ROLLE LAGT TIL I LISTEN: amuhmsmiljogruppa
        List<String> deptRoles = Arrays.asList(
                "serviceavdelingen",
                "automasjonsavdelingen",
                "prosjektavdelingen",
                "administrasjonen",
                "kbs_alle",
                "amuhmsmiljogruppa"
        );

        for (User u : sanitizedList) {
            if (u.getEmail().equalsIgnoreCase(myEmail)) {
                finalResult.add(u);
                continue;
            }

            boolean sharesDepartment = false;
            for (String role : u.getRoles()) {
                String r = role.toLowerCase();
                if (deptRoles.contains(r) && myRoles.contains(r)) {
                    sharesDepartment = true;
                    break;
                }
            }

            if (sharesDepartment) {
                finalResult.add(u);
            }
        }

        return finalResult;
    }

    private static List<String> getRolesForEmail(List<User> users, String email) {
        List<String> roles = new ArrayList<>();
        for (User u : users) {
            if (u.getEmail().equalsIgnoreCase(email)) {
                if (u.getRoles() != null) {
                    for (String r : u.getRoles()) roles.add(r.toLowerCase());
                }
                break;
            }
        }
        return roles;
    }
}