package com.project.whatsappchatbot.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.Base64;

@Service
public class RazorpayService {

    @Value("${razorpay.keyId}")
    private String keyId;

    @Value("${razorpay.keySecret}")
    private String keySecret;

    @Value("${razorpay.api.url}")
    private String razorpayApiUrl;

    public String createPaymentLink(double amount, String currency, String description, String customerName, String customerEmail, String customerContact) {
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        String auth = keyId + ":" + keySecret;
        byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes());
        String authHeader = "Basic " + new String(encodedAuth);
        headers.set("Authorization", authHeader);
        headers.set("Content-Type", "application/json");

        Map<String, Object> request = new HashMap<>();
        request.put("amount", amount * 100);
        request.put("currency", currency);
        request.put("description", description);

        Map<String, Object> customer = new HashMap<>();
        customer.put("name", customerName);
        customer.put("email", customerEmail);
        customer.put("contact", customerContact);

        request.put("customer", customer);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

        ResponseEntity<Map> response = restTemplate.exchange(
                UriComponentsBuilder.fromHttpUrl(razorpayApiUrl).toUriString(),
                HttpMethod.POST,
                entity,
                Map.class
        );

        if (response.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> responseBody = response.getBody();
            return (String) responseBody.get("short_url");
        } else {
            throw new RuntimeException("Failed to create payment link");
        }
    }
}
