package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.example.demo.service.EmailService;
import com.example.demo.service.OtpStore;


@RestController
@RequestMapping("/api/email")
public class EmailController {
	
	@Autowired
	private OtpStore otpStore;

	

    @Autowired
    private EmailService emailService;
    
    @PostMapping("/check")
    public ResponseEntity<?> check(@RequestParam String email){
    	if (emailService.isValidEmail(email) == false) {
            return ResponseEntity.status(429).body("Invalid Email Detected.");
        }
    	
    	if (emailService.isEmailTaken(email)) {
            return ResponseEntity.status(409).body("An account with this email already exists.");
        }
    	
    	 return ResponseEntity.ok().build();
    }

    @PostMapping("/send")
    public ResponseEntity<?> send(@RequestParam String email) {
        try {
            emailService.sendOtpEmail(email);
            return ResponseEntity.ok().build();
        } catch (RuntimeException e) {
            return ResponseEntity.status(500).body("Failed to send verification email.");
        }
    }

    
    @PostMapping("/verify")
    public ResponseEntity<String> verify(@RequestParam String email, @RequestParam String otp) {
        if (otpStore.validate(email, otp)) {
            otpStore.clear(email);

            return ResponseEntity.ok("Verified!");
        } else {
            return ResponseEntity.status(400).body("Invalid or expired code.");
        }
    }
}
