package com.zioinfo.mall.auth;

import com.zioinfo.mall.auth.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class AuthService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    public String login(String username, String password) {
        MallUser user = userMapper.findByUsername(username);
        if (user == null || !user.isActive()) {
            throw new RuntimeException("ERR-AUTH-001: 존재하지 않거나 비활성 계정");
        }
        if (!passwordEncoder.matches(password, user.getPasswordHash())) {
            throw new RuntimeException("ERR-AUTH-002: 비밀번호 불일치");
        }
        return jwtUtil.generate(username, user.getRole());
    }

    /** 고객 셀프 회원가입 — 항상 USER 역할로 생성. */
    public String register(String username, String password, String displayName) {
        if (username == null || username.isBlank() || password == null || password.isBlank()) {
            throw new IllegalArgumentException("ERR-AUTH-400: username/password 필수");
        }
        if (userMapper.countByUsername(username) > 0) {
            throw new RuntimeException("ERR-AUTH-409: 이미 존재하는 아이디");
        }
        MallUser user = new MallUser();
        user.setUsername(username);
        user.setPasswordHash(passwordEncoder.encode(password));
        user.setRole("USER");
        user.setDisplayName(displayName == null || displayName.isBlank() ? username : displayName);
        user.setActive(true);
        userMapper.insert(user);
        return jwtUtil.generate(username, "USER");
    }

    public Map<String, String> me(String token) {
        String username = jwtUtil.getUsername(token);
        String role = jwtUtil.getRole(token);
        return Map.of("username", username, "role", role);
    }
}
