package com.devjob.user.service;

import com.devjob.user.domain.Member;
import com.devjob.user.domain.Role;
import com.devjob.user.dto.MemberJoinRequest;
import com.devjob.user.dto.MemberResponse;
import com.devjob.common.exception.BusinessException;
import com.devjob.common.exception.ErrorCode;
import com.devjob.user.repository.MemberRepository;
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 MemberService {

    private final MemberRepository memberRepository;
    private final PasswordEncoder passwordEncoder;

    public Member findById(Long id) {
        return memberRepository.findById(id)
                .orElseThrow(() -> new BusinessException(ErrorCode.MEMBER_NOT_FOUND));
    }

    @Transactional
    public MemberResponse join(MemberJoinRequest req) {
        if (memberRepository.existsByEmail(req.email())) {
            throw new BusinessException(ErrorCode.DUPLICATE_EMAIL);
        }

        Member member = Member.builder()
                .email(req.email())
                .password(passwordEncoder.encode(req.password()))
                .role(Role.USER)
                .build();

        return MemberResponse.from(memberRepository.save(member));
    }
}
