package org.raddatz.familienarchiv.user;

import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.HexFormat;
import java.util.Optional;

import org.raddatz.familienarchiv.auth.AuthService;
import org.raddatz.familienarchiv.user.ResetPasswordRequest;
import org.raddatz.familienarchiv.exception.DomainException;
import org.raddatz.familienarchiv.exception.ErrorCode;
import org.raddatz.familienarchiv.user.AppUser;
import org.raddatz.familienarchiv.user.PasswordResetToken;
import org.raddatz.familienarchiv.user.PasswordResetTokenRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@RequiredArgsConstructor
@Slf4j
public class PasswordResetService {

    private final UserService userService;
    private final PasswordResetTokenRepository tokenRepository;
    private final PasswordEncoder passwordEncoder;
    private final AuthService authService;

    @Autowired(required = false)
    private JavaMailSender mailSender;

    @Value("${app.mail.from:noreply@familienarchiv.local}")
    private String mailFrom;

    private static final SecureRandom SECURE_RANDOM = new SecureRandom();
    private static final int TOKEN_EXPIRY_HOURS = 1;

    /**
     * Creates a reset token for the given email address and sends it via email.
     * If the email is not found, silently does nothing (prevents user enumeration).
     * If no mail sender is configured, logs a warning.
     */
    public void requestReset(String email, String appBaseUrl) {
        Optional<AppUser> userOpt = userService.findByEmailOptional(email);
        if (userOpt.isEmpty()) {
            log.debug("Password reset requested for unknown email: {}", email);
            return;
        }

        AppUser user = userOpt.get();
        String token = generateToken();

        tokenRepository.save(PasswordResetToken.builder()
                .user(user)
                .token(token)
                .expiresAt(LocalDateTime.now().plusHours(TOKEN_EXPIRY_HOURS))
                .build());

        sendResetEmail(user.getEmail(), token, appBaseUrl);
    }

    /**
     * Validates the token and updates the user's password.
     */
    @Transactional
    public void resetPassword(ResetPasswordRequest request) {
        PasswordResetToken resetToken = tokenRepository.findByToken(request.getToken())
                .orElseThrow(() -> DomainException.badRequest(
                        ErrorCode.INVALID_RESET_TOKEN, "Invalid or unknown reset token"));

        if (resetToken.isUsed() || resetToken.getExpiresAt().isBefore(LocalDateTime.now())) {
            throw DomainException.badRequest(ErrorCode.INVALID_RESET_TOKEN, "Token expired or already used");
        }

        AppUser user = resetToken.getUser();
        user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        userService.save(user);

        resetToken.setUsed(true);
        tokenRepository.save(resetToken);

        authService.revokeAllSessions(user.getEmail());
    }

    /**
     * Returns the raw token string of the most recent active (unused, unexpired)
     * reset token for the given email, if any. Used by the e2e helper to drive
     * automated password-reset flows; production code paths never call this.
     */
    public Optional<String> findLatestActiveTokenForEmail(String email) {
        return tokenRepository.findLatestActiveTokenByEmail(email, LocalDateTime.now());
    }

    /** Nightly cleanup of expired and used tokens. */
    @Scheduled(cron = "0 0 3 * * *")
    @Transactional
    public void cleanupExpiredTokens() {
        tokenRepository.deleteExpiredAndUsed(LocalDateTime.now());
        log.info("Cleaned up expired password reset tokens");
    }

    private String generateToken() {
        byte[] bytes = new byte[32];
        SECURE_RANDOM.nextBytes(bytes);
        return HexFormat.of().formatHex(bytes);
    }

    private void sendResetEmail(String to, String token, String appBaseUrl) {
        if (mailSender == null) {
            log.warn("Mail sender not configured — skipping password reset email to {}", to);
            return;
        }

        String resetUrl = appBaseUrl + "/reset-password?token=" + token;
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailFrom);
        message.setTo(to);
        message.setSubject("Passwort zurücksetzen — Familienarchiv");
        message.setText(
                "Hallo,\n\n"
                + "Sie haben eine Passwort-Zurücksetzung beantragt.\n\n"
                + "Klicken Sie auf den folgenden Link, um Ihr Passwort zurückzusetzen:\n"
                + resetUrl + "\n\n"
                + "Der Link ist " + TOKEN_EXPIRY_HOURS + " Stunde(n) gültig.\n\n"
                + "Falls Sie diese Anfrage nicht gestellt haben, ignorieren Sie diese E-Mail.\n\n"
                + "Ihr Familienarchiv-Team");

        try {
            mailSender.send(message);
            log.info("Password reset email sent to {}", to);
        } catch (MailException e) {
            log.error("Failed to send password reset email to {}: {}", to, e.getMessage());
        }
    }
}
