package com.yimeng.okr.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yimeng.okr.dto.LoginRequest;
import com.yimeng.okr.dto.LoginResponse;
import com.yimeng.okr.dto.RegisterRequest;
import com.yimeng.okr.dto.UserInfo;
import com.yimeng.okr.entity.SysUser;
import com.yimeng.okr.enums.UserRole;
import com.yimeng.okr.exception.BusinessException;
import com.yimeng.okr.mapper.SysUserMapper;
import com.yimeng.okr.security.JwtTokenProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class AuthService {

    private final SysUserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtTokenProvider tokenProvider;

    @Value("${app.super-admin.username}")
    private String superAdminUsername;

    @Value("${app.super-admin.password}")
    private String superAdminPassword;

    @Value("${app.super-admin.real-name}")
    private String superAdminRealName;

    public LoginResponse login(LoginRequest request) {
        SysUser user = userMapper.selectOne(
                new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, request.getUsername()));
        if (user == null) {
            throw new BusinessException(401, "用户名或密码错误");
        }
        if (!passwordEncoder.matches(request.getPassword(), user.getPasswordHash())) {
            throw new BusinessException(401, "用户名或密码错误");
        }
        if ("DISABLED".equals(user.getStatus()) || "LEFT".equals(user.getStatus())) {
            throw new BusinessException(403, "账号已禁用或离职，无法登录");
        }
        String accessToken = tokenProvider.generateAccessToken(user.getId(), user.getUsername(), user.getRole().name());
        String refreshToken = tokenProvider.generateRefreshToken(user.getId());
        return new LoginResponse(accessToken, refreshToken, UserInfo.from(user));
    }

    @Transactional
    public LoginResponse register(RegisterRequest request) {
        long count = userMapper.selectCount(
                new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, request.getUsername()));
        if (count > 0) {
            throw new BusinessException("用户名已存在");
        }
        SysUser user = new SysUser();
        user.setUsername(request.getUsername());
        user.setPasswordHash(passwordEncoder.encode(request.getPassword()));
        user.setRealName(request.getRealName());
        user.setEmail(request.getEmail());
        user.setPosition(request.getPosition());
        user.setDepartmentId(request.getDepartmentId());
        user.setSuperiorId(request.getSuperiorId());
        user.setRole(UserRole.EMPLOYEE);
        user.setStatus("ACTIVE");
        userMapper.insert(user);

        String accessToken = tokenProvider.generateAccessToken(user.getId(), user.getUsername(), user.getRole().name());
        String refreshToken = tokenProvider.generateRefreshToken(user.getId());
        return new LoginResponse(accessToken, refreshToken, UserInfo.from(user));
    }

    public UserInfo getMe(Long userId) {
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(404, "用户不存在");
        }
        return UserInfo.from(user);
    }

    public void changePassword(Long userId, String oldPassword, String newPassword) {
        SysUser user = userMapper.selectById(userId);
        if (user == null) throw new BusinessException(404, "用户不存在");
        if (!passwordEncoder.matches(oldPassword, user.getPasswordHash())) {
            throw new BusinessException("原密码错误");
        }
        user.setPasswordHash(passwordEncoder.encode(newPassword));
        userMapper.updateById(user);
    }

    public String refreshAccessToken(String refreshToken) {
        if (refreshToken == null || !tokenProvider.validateToken(refreshToken)) {
            throw new BusinessException(401, "Token已过期，请重新登录");
        }
        Long userId = tokenProvider.getUserIdFromToken(refreshToken);
        SysUser user = userMapper.selectById(userId);
        if (user == null) throw new BusinessException(401, "用户不存在，请重新登录");
        return tokenProvider.generateAccessToken(user.getId(), user.getUsername(), user.getRole().name());
    }

    @Transactional
    public void initAdmin() {
        long count = userMapper.selectCount(
                new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, superAdminUsername));
        if (count == 0) {
            SysUser admin = new SysUser();
            admin.setUsername(superAdminUsername);
            admin.setPasswordHash(passwordEncoder.encode(superAdminPassword));
            admin.setRealName(superAdminRealName);
            admin.setEmail("admin@emoon.com");
            admin.setRole(UserRole.SUPER_ADMIN);
            admin.setStatus("ACTIVE");
            userMapper.insert(admin);
        }
    }
}
