package org.cmh.backend.authentication.service;

import org.cmh.backend.UserManagement.model.Tenant;
import org.cmh.backend.UserManagement.repository.TenantManagementRepository;
import org.cmh.backend.authentication.dto.ChangePasswordRequest;
import org.cmh.backend.authentication.dto.ManageUserProfileRequest;
import org.cmh.backend.authentication.dto.RegisterRequest;
import org.cmh.backend.authentication.model.UserHS;
import org.cmh.backend.authentication.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private TenantManagementRepository tenantRepository;

    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public UserHS getUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public boolean registerUser(RegisterRequest request) {
        String username = request.getUsername();
        String password = request.getPassword();
        String phoneNumber = request.getPhoneNumber();
        // 验证用户名是否已存在
        if (userRepository.findByUsername(username) != null) {
            return false; // 用户已存在
        }

        // 验证输入格式
        if (!isValidUsername(username) || !isValidPassword(password) || !isValidContactInfo(phoneNumber)) {
            throw new IllegalArgumentException();
        }

        // 加密密码
        String encodedPassword = passwordEncoder.encode(password);

        // 创建新用户
        UserHS newUser = new UserHS();
        newUser.setUsername(username);
        newUser.setPassword(encodedPassword);
        newUser.setPhoneNumber(phoneNumber);
        newUser.setRole("企业管理员");
        newUser.setTenant(username);
        newUser.setGender("男");
        newUser.setNickname(username);
        newUser.setEmail("user@example.com");
        newUser.setDepartment("企业管理员");
        newUser.setCreatedAt(LocalDateTime.now());

        userRepository.save(newUser);

        Tenant newTenant = new Tenant();
        newTenant.setName(username);
        newTenant.setPhone(phoneNumber);
        newTenant.setManager(username);
        newTenant.setSymbol(username);
        newTenant.setContact(username);
        tenantRepository.save(newTenant);

        return true;
    }

    public boolean addUser(UserHS user) {
        String username = user.getUsername();
        String password = user.getPassword();
        String phoneNumber = user.getPhoneNumber();
        // 验证用户名是否已存在
        if (userRepository.findByUsername(username) != null) {
            return false; // 用户已存在
        }

        // 验证输入格式
        if (!isValidUsername(username) || !isValidPassword(password) || !isValidContactInfo(phoneNumber)) {
            throw new IllegalArgumentException();
        }

        // 加密密码
        String encodedPassword = passwordEncoder.encode(password);
        user.setPassword(encodedPassword);

        userRepository.save(user);
        return true;
    }

    public boolean deleteUser(String username){
        return userRepository.deleteByUsername(username);
    }

    public List<UserHS> getAllUsers() {
        return userRepository.findAll();
    }

    public List<UserHS> getUsersByTenant(String tenant){
        return userRepository.findByTenant(tenant);
    }

    public boolean loginUser(String username, String password) {
        UserHS user = userRepository.findByUsername(username);
        return user != null && passwordEncoder.matches(password, user.getPassword());
    }

    public boolean updateUserProfile(String username, ManageUserProfileRequest request) {
        UserHS user = userRepository.findByUsername(username);
        if (user != null) {
            user.setNickname(request.getNickname());
            user.setGender(request.getGender());
            user.setPhoneNumber(request.getPhoneNumber());
            user.setEmail(request.getEmail());
            user.setDepartment(request.getDepartment());
            user.setRole(request.getRole());
            try {
                userRepository.save(user);
            } catch (Exception e) {
                return false;
            }
            return true;
        } else {
            return false;
        }
    }

    public boolean changePassword(String username, ChangePasswordRequest request) {
        UserHS user = userRepository.findByUsername(username);
        if (user != null) {
            if (passwordEncoder.matches(request.getCurrentPassword(), user.getPassword())) {
                if (isValidPassword(request.getNewPassword())) {
                    String encodedPassword = passwordEncoder.encode(request.getNewPassword());
                    user.setPassword(encodedPassword);
                    try {
                        userRepository.save(user);
                    } catch (Exception e) {
                        return false;
                    }
                    return true;
                }
            }
        }
        return false;
    }


    // 验证用户名格式
    private boolean isValidUsername(String username) {
        return username != null && username.length() >= 3 && username.length() <= 20;
    }

    // 验证密码格式
    private boolean isValidPassword(String password) {
        return password != null && password.length() >= 4;
    }

    // 验证联系方式格式（假设为电话号码）
    private boolean isValidContactInfo(String contactInfo) {
        String regex = "^\\+?[0-9. ()-]{7,25}$"; // 电话号码验证
        return contactInfo != null && Pattern.matches(regex, contactInfo);
    }

}