package com.micer.easyball.service.Impl;

import com.alibaba.fastjson.JSON;
import com.micer.easyball.pojo.Dto.WeatherDto;
import com.micer.easyball.pojo.ResponseResult;
import com.micer.easyball.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WeatherServiceImpl implements WeatherService {

    @Autowired
    private RestTemplate restTemplate;

    // 写死一个一定能返回成功响应的 URL
    // 使用 httpbin.org 的 /get 接口，它会原样返回请求参数
    // 实际攻击场景中，攻击者会劫持这个 URL 指向恶意服务器
    private static final String WEATHER_API_URL =
            "https://httpbin.org/get?temperature=25°C&condition=晴朗&iconUrl=https://example.com/sunny.png&alert=正常";

    @Override
    public ResponseResult getWeather(String city, String gameDate) {
        // 直接调用第三方 API，未校验响应
        String response = restTemplate.getForObject(WEATHER_API_URL, String.class);

        // 直接解析 JSON 响应（不安全：信任第三方数据）
        // httpbin.org 返回的格式是 {"args": {"temperature": "25°C", ...}}
        // 我们模拟解析成 WeatherDto
        WeatherDto weather = parseResponse(response);

        return new ResponseResult(200, "成功", weather);
    }

    private WeatherDto parseResponse(String response) {
        // 简化解析：直接构造一个 WeatherDto，实际场景中会用 JSON.parseObject
        // 这里故意模拟"直接信任第三方数据"的漏洞
        WeatherDto weather = new WeatherDto();
        weather.setTemperature("25°C");
        weather.setCondition("晴朗");
        weather.setIconUrl("https://example.com/sunny.png");
        weather.setAlert("正常");
        return weather;
    }
}