package com.project.whatsappchatbot.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class OtpServiceTemplate {

    @Value("${WHATSAPP_API_URL}")
    public String WHATSAPP_API_URL;

    @Value("${WHATSAPP_API_TOKEN}")
    public String WHATSAPP_API_TOKEN;

    @Value("${WHATSAPP_API_TOKEN}")
    private String VERIFY_TOKEN;

    @Autowired
    private RestTemplate restTemplate;

    public void sendOtpMessage(String to, String otp) {
        HttpHeaders headers = new HttpHeaders();
        headers.setBearerAuth(WHATSAPP_API_TOKEN);
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> messageBody = new HashMap<>();
        messageBody.put("messaging_product", "whatsapp");
        messageBody.put("to", to);
        messageBody.put("type", "template");

        Map<String, Object> template = new HashMap<>();
        template.put("name", "otp_auth");
        template.put("language", Map.of("code", "en"));

        List<Map<String, Object>> components = new ArrayList<>();

        Map<String, Object> bodyComponent = new HashMap<>();
        bodyComponent.put("type", "body");
        bodyComponent.put("parameters", List.of(
                Map.of("type", "text", "text", otp)
        ));
        components.add(bodyComponent);

        Map<String, Object> buttonComponent = new HashMap<>();
        buttonComponent.put("type", "button");
        buttonComponent.put("sub_type", "url");
        buttonComponent.put("index", "0");
        buttonComponent.put("parameters", List.of(
                Map.of("type", "text", "text", otp)
        ));
        components.add(buttonComponent);
        template.put("components", components);
        messageBody.put("template", template);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(messageBody, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(WHATSAPP_API_URL, request, String.class);
        System.out.println("send otp: " + to + " response: " + response.getBody() + " errorcode: "+ response.getStatusCode());
    }

}