package com.realnet.users.service;

import com.realnet.users.entity.User;
import com.realnet.users.model.LoginRequest;
import com.realnet.users.model.RegisterRequest;
import com.realnet.users.repository.UserRepository;
import com.realnet.users.util.JwtUtil; // Assuming this will be created in 1.6
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class AuthService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager; // Assuming this is configured by Spring Security

    @Autowired
    private JwtUtil jwtUtil; // Assuming this will be created in 1.6

    public User registerUser(RegisterRequest registerRequest) {
        if (userRepository.existsByUsername(registerRequest.getUsername())) {
            throw new RuntimeException("Error: Username is already taken!");
        }

        if (userRepository.existsByEmail(registerRequest.getEmail())) {
            throw new RuntimeException("Error: Email is already in use!");
        }

        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setEmail(registerRequest.getEmail());
        user.setPasswordHash(passwordEncoder.encode(registerRequest.getPassword()));
        user.setStatus("offline"); // Default status
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        return userRepository.save(user);
    }

    public String authenticateUserAndGenerateJwt(LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);
        // Assuming UserDetailsImpl is returned by UserDetailsService
        // User userDetails = (User) authentication.getPrincipal(); // This might need casting to a custom UserDetails implementation
        // For now, just use the username from the request
        return jwtUtil.generateToken(loginRequest.getUsername()); // Generate token using username
    }
}