package com.spring.domain.user.service;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.domain.user.dto.ChangePasswordRequest;
import com.spring.domain.user.entity.AgentUser;
import com.spring.domain.user.error.EmailMismatchException;
import com.spring.domain.user.error.PasswordSameException;
import com.spring.domain.user.error.UserNotFoundException;
import com.spring.domain.user.repository.AgentUserRepository;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class ChangePasswordService {
    
    private final AgentUserRepository agentUserRepository;
    private final PasswordEncoder passwordEncoder;

    @Transactional
    public void changePassword(ChangePasswordRequest request) {
        AgentUser user = agentUserRepository.findByUserId(request.getUserId()).orElseThrow(UserNotFoundException::new);
        if (!user.getEmail().equals(request.getEmail())) {
            throw new EmailMismatchException();
        }
        if (passwordEncoder.matches(request.getNewPassword(), user.getPassword())) {
            throw new PasswordSameException();
        }
        user.changePassword(passwordEncoder.encode(request.getNewPassword()));
    }

}
