package com.devjob.user.service;

import com.devjob.user.domain.Member;
import com.devjob.user.dto.LoginRequest;
import com.devjob.user.dto.LoginResponse;
import com.devjob.common.exception.BusinessException;
import com.devjob.common.exception.ErrorCode;
import com.devjob.user.repository.MemberRepository;
import com.devjob.common.security.JwtProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class AuthService {

    private final MemberRepository memberRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtProvider jwtProvider;

    public LoginResponse login(LoginRequest request) {
        Member member = memberRepository.findByEmail(request.email())
                .orElseThrow(() -> new BusinessException(ErrorCode.MEMBER_NOT_FOUND));

        if (!passwordEncoder.matches(request.password(), member.getPassword())) {
            throw new BusinessException(ErrorCode.INVALID_PASSWORD);
        }

        String accessToken = jwtProvider.createToken(member.getId(), member.getRole().name());
        return LoginResponse.of(accessToken, member.getId(), member.getEmail(), member.getRole());
    }
}
