package com.zioinfo.cms.auth;

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

import java.util.HashMap;
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) {
        CmsUser 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());
    }

    public Map<String, Object> me(String token) {
        String username = jwtUtil.getUsername(token);
        String role = jwtUtil.getRole(token);
        CmsUser u = userMapper.findByUsername(username);
        Map<String, Object> m = new HashMap<>();
        m.put("username", username);
        m.put("role", role);
        m.put("displayName", u != null ? u.getDisplayName() : username);
        return m;
    }
}
