package com.maternalmall.service;

import com.maternalmall.common.BizException;
import com.maternalmall.domain.User;
import com.maternalmall.domain.UserRole;
import com.maternalmall.repository.UserRepository;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class AuthService {
    private final UserRepository userRepository;

    public AuthService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public Map<String, Object> register(String username, String password, String role) {
        username = username == null ? "" : username.trim();
        password = password == null ? "" : password.trim();
        if (username.isEmpty()) {
            throw new BizException("用户名不能为空");
        }
        if (password.isEmpty()) {
            throw new BizException("密码不能为空");
        }
        userRepository.findByUsername(username).ifPresent(u -> {
            throw new BizException("账号已存在");
        });
        if (role != null && !role.isBlank() && !"CUSTOMER".equalsIgnoreCase(role)) {
            throw new BizException("仅支持注册顾客账号，商家需提交入驻申请");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(UserRole.CUSTOMER);
        user.setNickname(username);
        userRepository.save(user);
        return Map.of("userId", user.getId());
    }

    public Map<String, Object> login(String username, String password) {
        User user = userRepository.findByUsername(username).orElseThrow(() -> new BizException("用户不存在"));
        if (!user.getPassword().equals(password)) {
            throw new BizException("密码错误");
        }
        if (!Boolean.TRUE.equals(user.getEnabled())) {
            throw new BizException("账号已被禁用，请联系管理员");
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        user.setToken(token);
        userRepository.save(user);

        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("id", user.getId());
        data.put("username", user.getUsername());
        data.put("role", user.getRole());
        data.put("nickname", user.getNickname());
        return data;
    }
}
