package com.example;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

@RestController
public class BankingAPI {
    private static final String SUSPICIOUS_TOPIC = "SUSPICIOUS_TOPIC";
    private static final String VALID_TOPIC = "VALID_TOPIC";
    @Autowired
    private Jedis jedis;
    @PostMapping("/check-transaction")
    public String checkTransaction(@RequestBody TransactionInfo transactionInfo) {
        String name = transactionInfo.getName();
        String location = transactionInfo.getLocation();
        double amount = transactionInfo.getAmount();
        String jsonObject = jedis.get(name);
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(jsonObject);
        String country = "";
        try {
            MyRecord jsonInfo = objectMapper.readValue(jsonObject, MyRecord.class);
             country = jsonInfo.getCountry();
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        System.out.println("country: "+country);
        System.out.println("location: "+location);
        if (country == null) {
            return "User not found in the database.";
        } else {
            if (country.equals(location)) {
                MyProducer.logTransaction(transactionInfo,VALID_TOPIC);
                return "Transaction is valid.";
            } else {
                MyProducer.logTransaction(transactionInfo,SUSPICIOUS_TOPIC);
                return "Transaction is suspicious.";
            }
        }
    }
}