package com.kt.distribution.adapter;

import com.kt.distribution.dto.ChannelDistributionResult;
import com.kt.distribution.dto.ChannelType;
import com.kt.distribution.dto.DistributionRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 우리동네TV Adapter
 * 우리동네TV API 호출
 *
 * @author System Architect
 * @since 2025-10-23
 */
@Slf4j
@Component
public class UriDongNeTvAdapter extends AbstractChannelAdapter {

    @Value("${channel.apis.uridongnetv.url}")
    private String apiUrl;

    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public ChannelType getChannelType() {
        return ChannelType.URIDONGNETV;
    }

    @Override
    protected ChannelDistributionResult executeDistribution(DistributionRequest request) {
        log.debug("Calling UriDongNeTV API: url={}, eventId={}", apiUrl, request.getEventId());

        // 외부 API 호출 준비
        Map<String, Object> payload = new HashMap<>();
        payload.put("eventId", request.getEventId());
        payload.put("title", request.getTitle());
        payload.put("videoUrl", request.getImageUrl()); // 이미지를 영상으로 변환한 URL
        payload.put("radius", getChannelSetting(request, "radius", "500m"));
        payload.put("timeSlot", getChannelSetting(request, "timeSlot", "evening"));

        // TODO: 실제 API 호출 (현재는 Mock)
        // ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl + "/distribute", payload, Map.class);

        // Mock 응답
        String distributionId = "UDTV-" + UUID.randomUUID().toString();
        int estimatedReach = 5000;

        return ChannelDistributionResult.builder()
                .channel(ChannelType.URIDONGNETV)
                .success(true)
                .distributionId(distributionId)
                .estimatedReach(estimatedReach)
                .build();
    }

    private String getChannelSetting(DistributionRequest request, String key, String defaultValue) {
        if (request.getChannelSettings() != null) {
            Map<String, Object> settings = request.getChannelSettings().get(ChannelType.URIDONGNETV.name());
            if (settings != null && settings.containsKey(key)) {
                return settings.get(key).toString();
            }
        }
        return defaultValue;
    }
}
