package com.MedInsuranceV2.Version20.Controller;
 // Import the new RegistrationService

// Import your custom exceptions
import exception.UserAlreadyExistsException;
import exception.AdminRegistrationRestrictedException;
import exception.EmailSendingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; // For AJAX response

import com.MedInsuranceV2.Version20.Email.RegistrationService;
import com.MedInsuranceV2.Version20.User.User;

import jakarta.servlet.http.HttpSession; // For session management, though mostly replaced by OtpService's temp storage

import java.util.HashMap;
import java.util.Map;

@Controller
public class RegistrationController {

    @Autowired
    private RegistrationService registrationService; // Inject the new RegistrationService

    // We don't need to inject OtpService directly here anymore if RegistrationService exposes getPendingUser

   

    @PostMapping("/sendOtpForRegistration")
    public String sendOtpForRegistration(@RequestParam String name,
                                         @RequestParam String mobileNumber,
                                         @RequestParam String emailId,
                                         @RequestParam String password,
                                         @RequestParam String confirmPassword,
                                         @RequestParam String role,
                                         Model model) throws AdminRegistrationRestrictedException {

        if (!password.equals(confirmPassword)) {
            model.addAttribute("error", "Passwords do not match.");
            model.addAttribute("name", name);
            model.addAttribute("mobileNumber", mobileNumber);
            model.addAttribute("emailId", emailId);
            model.addAttribute("role", role);
            return "register";
        }

        try {
            User pendingUser = registrationService.prepareUserForRegistration(name, mobileNumber, emailId, password, role);
            registrationService.generateAndSendRegistrationOtp(emailId, role, pendingUser);

            // THESE LINES ARE CRUCIAL FOR DISPLAYING THE OTP SECTION
            model.addAttribute("successMessage", "OTP sent to " + emailId + ". Please check your email.");
            model.addAttribute("showOtpSection", true); // <--- This must be true
            model.addAttribute("emailId", emailId);     // <--- The email to display and use in hidden field
            model.addAttribute("role", role);           // <--- The role to use in hidden field
            return "register";

        } catch (UserAlreadyExistsException | EmailSendingException e) {
            model.addAttribute("error", e.getMessage());
            model.addAttribute("name", name);
            model.addAttribute("mobileNumber", mobileNumber);
            model.addAttribute("emailId", emailId);
            model.addAttribute("role", role);
            return "register";
        } catch (Exception e) {
            System.err.println("An unexpected error occurred during registration initiation: " + e.getMessage());
            e.printStackTrace();
            model.addAttribute("error", "An unexpected error occurred during registration. Please try again.");
            model.addAttribute("name", name);
            model.addAttribute("mobileNumber", mobileNumber);
            model.addAttribute("emailId", emailId);
            model.addAttribute("role", role);
            return "register";
        }
    }
    @PostMapping("/verifyOtpAndRegister")
    public String verifyOtpAndRegister(@RequestParam String otp, @RequestParam String emailId, HttpSession session) {
        if (emailId == null || emailId.isEmpty()) {
            throw new RuntimeException("Email is missing. Please provide a valid email.");
        }
        System.out.println("Email received for OTP verification: " + emailId);
        registrationService.verifyAndCompleteRegistration(emailId, otp);
        return "redirect:/login"; // Redirect to login page after successful registration
    }


    @PostMapping("/resendOtpForRegistration")
    @ResponseBody // This annotation tells Spring to return the Map as JSON directly
    public Map<String, Object> resendOtpForRegistration(@RequestParam String emailId, @RequestParam String role) {
        Map<String, Object> response = new HashMap<>();
        try {
            // Retrieve the pending user associated with this email from the RegistrationService
            User pendingUser = registrationService.getPendingUser(emailId);
            if (pendingUser == null) {
                response.put("success", false);
                response.put("message", "Registration session expired. Please restart registration.");
                return response;
            }
            // Call Registration Service to regenerate and resend OTP using the same pending user object
            registrationService.generateAndSendRegistrationOtp(emailId, role, pendingUser);
            response.put("success", true);
            response.put("message", "New OTP sent successfully!");
        } catch (EmailSendingException e) {
            response.put("success", false);
            response.put("message", "Failed to resend OTP: " + e.getMessage());
        } catch (Exception e) {
             System.err.println("Error resending OTP for " + emailId + ": " + e.getMessage());
             e.printStackTrace();
             response.put("success", false);
             response.put("message", "An unexpected error occurred while trying to resend OTP.");
        }
        return response;
    }
}
