package service;

import model.User;
import model.UserType;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;



public class UserManager {
    private final Path usersFile = Paths.get("data", "users.txt");
    private final Map<String, User> usersByEmail = new HashMap<>(); // 使用邮箱作为主键

    public UserManager() {
        try {
            Files.createDirectories(usersFile.getParent());
            if (!Files.exists(usersFile)) Files.createFile(usersFile);
            loadUsers();
        } catch (IOException e) {
            System.err.println("初始化用户管理器时出错: " + e.getMessage());
        }
    }

    private void loadUsers() throws IOException {
        List<String> lines = Files.readAllLines(usersFile, StandardCharsets.UTF_8);
        for (String line : lines) {
            User user = User.fromString(line);
            if (user != null) usersByEmail.put(user.getEmail(), user);
        }
    }

    private void saveUsers() {
        try (BufferedWriter writer = Files.newBufferedWriter(usersFile, StandardCharsets.UTF_8)) {
            for (User user : usersByEmail.values()) writer.write(user.toString() + "\n");
        } catch (IOException e) {
            System.err.println("保存用户时出错: " + e.getMessage());
        }
    }



    public User authenticate(String identifier, String password) {
        String hashedInput = hashPassword(password);

        // 策略一：尝试将 identifier 作为邮箱进行快速查找
        User userByEmail = usersByEmail.get(identifier);
        if (userByEmail != null && userByEmail.getHashedPassword().equals(hashedInput)) {
            return userByEmail; // 邮箱匹配成功
        }

        // 策略二：如果邮箱查找失败，则遍历所有用户，尝试匹配用户名
        for (User user : usersByEmail.values()) {
            if (user.getUsername() != null && user.getUsername().equals(identifier)) {
                if (user.getHashedPassword().equals(hashedInput)) {
                    return user; // 用户名匹配成功
                }
                break; // 用户名是唯一的，找到后无需继续遍历
            }
        }

        return null; // 认证失败
    }

    public boolean emailExists(String email) {
        return usersByEmail.containsKey(email);
    }

    public boolean usernameExists(String username) {
        if (username == null || username.trim().isEmpty()) return false;
        for (User user : usersByEmail.values()) {
            if (username.equals(user.getUsername())) {
                return true;
            }
        }
        return false;
    }

    public void registerUser(String email, String username, String password, UserType type) {
        User newUser = new User(email, username, "", type);
        newUser.setHashedPassword(password);
        usersByEmail.put(email, newUser);
        saveUsers();
    }

    public void updateUser(User user) {
        if (usersByEmail.containsKey(user.getEmail())) {
            usersByEmail.put(user.getEmail(), user);
            saveUsers();
        }
    }

    private String hashPassword(String password) {
        return Integer.toString(password.hashCode());
    }
}