package com.project.whatsappchatbot.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.whatsappchatbot.DTO.LoginRequest;
import com.project.whatsappchatbot.DTO.OTPDetails;
import com.project.whatsappchatbot.model.OtpRequest;
import com.project.whatsappchatbot.service.AccountService;
import com.project.whatsappchatbot.service.LaravelTokenService;
import com.project.whatsappchatbot.service.SendOtpService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/otp")
public class OtpController {

  @Autowired AccountService accountService;
  // @Autowired
  // private AccountRepository accountRepository;
  // ────────────────────────────────────────────────────────────
  // Removed: UserDetailsServiceImpl and JwtUtils — they are no
  // longer needed for token generation in this controller.
  // ────────────────────────────────────────────────────────────
  @Autowired private SendOtpService sendOtpService;
  @Autowired private LaravelTokenService tokenService; // ➋ NEW

  @GetMapping("user-exists/{phone}")
  public ResponseEntity<Boolean> checkIfUserExists(@PathVariable String phone) {
//	  return accountService.checkIfUserExists(phone);
    return null;
  }

  // ────────────────────────────────────────────────────────────
  @PostMapping("/send-otp")
  public ResponseEntity<Map<String, Object>> sentOtp(
      @RequestBody LoginRequest loginRequest, HttpServletRequest request) {
    return sendOtpService.requestOtp(loginRequest, request);
  }

  // ────────────────────────────────────────────────────────────
  // STEP 2 – verify OTP and fetch JWT from Laravel
  // ────────────────────────────────────────────────────────────
  @PostMapping("/verify-otp")
  public CompletableFuture<ResponseEntity<Map<String, Object>>> verifyOtp(
      @RequestBody OtpRequest otpRequest) {

    Map<String, Object> response = new LinkedHashMap<>();
    String phone = otpRequest.getPhone();

    // Defensive checks
    if (phone == null) {
      response.put("success", false);
      response.put("error", "Session expired or invalid.");
      return CompletableFuture.completedFuture(
          ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response));
    }

    OTPDetails otpDetails = SendOtpService.otpMap.get(phone);
    if (otpDetails == null || otpDetails.getTimestamp().isBefore(LocalDateTime.now())) {
      response.put("success", false);
      response.put("error", "Otp expired or not found.");
      return CompletableFuture.completedFuture(
          ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response));
    }

    if (!otpRequest.getOtp().equals(otpDetails.getOtp())) {
      response.put("success", false);
      response.put("error", "Otp mismatch.");
      return CompletableFuture.completedFuture(
          ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response));
    }
    
    if(otpRequest.getType() != null && otpRequest.getType().equalsIgnoreCase("login") ) {
    	// ───────────────────────────────────────────────────
    	// OTP verified → request JWT from Laravel
    	// ───────────────────────────────────────────────────
    	return tokenService
    			.getJwtFromLaravel(phone)
    			.thenApply(
    					res -> {
    						if (res.getStatusCode() == HttpStatus.OK) {
    							ObjectMapper objectMapper = new ObjectMapper();
    							try {
    								Map<String, Object> body = objectMapper.readValue(res.getBody(), Map.class);
    								return ResponseEntity.ok(body);
    							} catch (JsonProcessingException e) {
    								Map<String, Object> error = new HashMap<>();
    								error.put("success", false);
    								error.put("error", "Invalid JSON");
    								return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
    							}
    						} else {
    							Map<String, Object> error = new HashMap<>();
    							error.put("success", false);
    							error.put("error", res.getBody());
    							return ResponseEntity.status(res.getStatusCode())
    									.headers(res.getHeaders())
    									.body(error);
    						}
    					})
    			.exceptionally(
    					ex -> {
    						Map<String, Object> errorResponse = new HashMap<>();
    						errorResponse.put("success", false);
    						String errorMessage =
    								ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage();
    								errorResponse.put("error", "Could not connect to Laravel service: " + errorMessage);
    								return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
    					});
    } else if(otpRequest.getType() != null && otpRequest.getType().equalsIgnoreCase("register") ) {
    	Map<String, Object> errorResponse = new HashMap<>();
    	errorResponse.put("success", true);
    	return CompletableFuture.completedFuture(
    			ResponseEntity.status(HttpStatus.OK).body(errorResponse));
    }
    response.put("success", false);
    response.put("error", "type mismatch.");
    return CompletableFuture.completedFuture(
        ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response));

  }
}
