package com.realnet.auth.service;

import com.realnet.auth.dto.AuthResponse;
import com.realnet.auth.dto.LoginRequest;
import com.realnet.auth.dto.PasswordResetRequest;
import com.realnet.auth.dto.RegisterRequest;
import com.realnet.auth.entity.PasswordResetToken;
import com.realnet.auth.entity.User;
import com.realnet.auth.repository.PasswordResetTokenRepository;
import com.realnet.auth.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtService jwtService;
    private final PasswordResetTokenRepository passwordResetTokenRepository;

    public AuthResponse register(RegisterRequest request) {
        var user = User.builder()
                .username(request.getUsername())
                .email(request.getEmail())
                .passwordHash(passwordEncoder.encode(request.getPassword()))
                .build();
        userRepository.save(user);
        var jwtToken = jwtService.generateToken(user);
        return AuthResponse.builder().token(jwtToken).build();
    }

    public AuthResponse login(LoginRequest request) {
        var user = userRepository.findByEmail(request.getEmail())
                .orElseThrow(() -> new RuntimeException("User not found")); // TODO: Custom exception

        if (!passwordEncoder.matches(request.getPassword(), user.getPasswordHash())) {
            throw new RuntimeException("Invalid credentials"); // TODO: Custom exception
        }

        var jwtToken = jwtService.generateToken(user);
        return AuthResponse.builder().token(jwtToken).build();
    }

    public void initiatePasswordReset(PasswordResetRequest request) {
        User user = userRepository.findByEmail(request.getEmail())
                .orElseThrow(() -> new RuntimeException("User not found")); // TODO: Custom exception

        String token = UUID.randomUUID().toString();
        PasswordResetToken resetToken = PasswordResetToken.builder()
                .token(token)
                .user(user)
                .expiryDate(LocalDateTime.now().plusMinutes(30)) // Token valid for 30 minutes
                .build();
        passwordResetTokenRepository.save(resetToken);

        // Placeholder for sending password reset email
        // In a real application, an email service would be used here to send a link
        // containing the token to the user's email address.
    }
}
