package com.imprimelibros.erp.auth;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;

import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import jakarta.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/auth/password")
@Validated
public class PasswordResetController {

    private final PasswordResetService service;
    private final MessageSource messageSource;

    public PasswordResetController(PasswordResetService service, MessageSource messageSource) {
        this.service = service;
        this.messageSource = messageSource;
    }

    // 4.1 Página "¿Olvidaste tu contraseña?"
    @GetMapping("/forgot")
    public String forgotForm(Model model, Locale locale) {
        model.addAttribute("form", "_forgot-password");
        return "imprimelibros/login/login";
    }

    // 4.2 Envío del email (si existe)
    @PostMapping("/forgot")
    public String handleForgot(
            @RequestParam @NotBlank @Email String username,
            HttpServletRequest request,
            Model model,
            RedirectAttributes ra,
            Locale locale) {
        String baseUrl = request.getScheme() + "://" + request.getServerName()
                + (request.getServerPort() == 80 || request.getServerPort() == 443 ? ""
                        : ":" + request.getServerPort());
        String ip = request.getRemoteAddr();
        String ua = request.getHeader("User-Agent");
        service.requestReset(username, baseUrl, ip, ua, 60, locale);

        ra.addFlashAttribute("info", messageSource.getMessage("login.password-recovery.email-info", null, locale));
        return "redirect:/login";
    }

    // 4.3 Formulario de nueva contraseña (a partir del enlace)
    @GetMapping("/reset")
    public String resetForm(@RequestParam("uid") Long uid,
            @RequestParam("token") String token,
            Model model, Locale locale) {
        boolean ok = service.isValid(uid, token);
        model.addAttribute("uid", uid);
        model.addAttribute("token", token);
        model.addAttribute("valid", ok);

        model.addAttribute("form", "_reset-password");
        return "imprimelibros/login/login";
    }

    // 4.4 Confirmación del reseteo
    @PostMapping("/reset")
    public String doReset(@RequestParam("uid") Long uid,
            @RequestParam("token") String token,
            @RequestParam("password") String password,
            @RequestParam("password2") String password2,
            Model model, Locale locale) {
        if (!password.equals(password2) || password.length() < 8) {
            model.addAttribute("uid", uid);
            model.addAttribute("token", token);
            model.addAttribute("danger", messageSource.getMessage("login.password-reset.error", null, locale));
            model.addAttribute("form", "_reset-password");
            return "imprimelibros/login/login";
        }
        if (service.resetPassword(uid, token, password)) {
            model.addAttribute("info", messageSource.getMessage("login.password-reset.success", null, locale));
        } else {
            model.addAttribute("danger", messageSource.getMessage("login.password-reset.error-link", null, locale));
        }
        model.addAttribute("form", "_login");
        return "imprimelibros/login/login";
    }
}
