package kz.konturai.parser.service;

import kz.konturai.parser.dto.FacebookAdAccountDto;
import kz.konturai.parser.dto.InstagramInsightDto;
import kz.konturai.parser.dto.TikTokCampaignDto;
import kz.konturai.parser.model.TargetingCampaign;
import kz.konturai.parser.model.TargetingInsight;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class TargetingInsightService {

//    private final FacebookAdsService facebookAdsService;
//    private final TikTokAdsService tikTokAdsService;
    private final SocialMediaCredentialsService credentialsService;

    public List<TargetingInsight> generateTargetingInsights(TargetingCampaign campaign) {
        log.info("Generating insights for campaign {}", campaign.getId());
        List<TargetingInsight> insights = new ArrayList<>();
        Map<String, String> externalIds = campaign.getExternalIds();
        
        if (externalIds == null || externalIds.isEmpty()) {
            log.warn("Campaign {} has no external IDs to fetch insights", campaign.getId());
            return insights;
        }

        String userId = campaign.getUserId();
        
        try {
//            if (externalIds.containsKey("FACEBOOK") || externalIds.containsKey("INSTAGRAM")) {
//                String fbToken = credentialsService.getCredentials(userId, "FACEBOOK");
//                if (fbToken != null) {
//                    String fbCampaignId = externalIds.getOrDefault("FACEBOOK", externalIds.get("INSTAGRAM"));
//                    InstagramInsightDto fbInsights = facebookAdsService.getInsights(fbToken, fbCampaignId, "last_3d");
//                    insights.add(buildInsight("FACEBOOK", "CTR", fbInsights.getCtr()));
//                    insights.add(buildInsight("FACEBOOK", "CPM", fbInsights.getCpm()));
//                    insights.add(buildInsight("FACEBOOK", "SPEND", fbInsights.getSpend()));
//                }
//            }
//            
//            if (externalIds.containsKey("TIKTOK")) {
//                String ttToken = credentialsService.getCredentials(userId, "TIKTOK");
//                if (ttToken != null) {
//                    String ttCampaignId = externalIds.get("TIKTOK");
//                    String today = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//                    // Let's assume advertiser_id is known or saved in credentials, use a placeholder here
//                    String advertiserId = "placeholder_adv_id"; 
//                    TikTokCampaignDto ttInsights = tikTokAdsService.getCampaignInsights(ttToken, advertiserId, ttCampaignId, today, today);
//                    insights.add(buildInsight("TIKTOK", "CTR", ttInsights.getCtr()));
//                    insights.add(buildInsight("TIKTOK", "CPM", ttInsights.getCpm()));
//                    insights.add(buildInsight("TIKTOK", "SPEND", ttInsights.getSpend()));
//                }
//            }
        } catch (Exception e) {
            log.error("Failed to generate targeting insights for campaign {}", campaign.getId(), e);
        }

        return insights;
    }

    private TargetingInsight buildInsight(String platform, String metric, Double value) {
        return TargetingInsight.builder()
                .platform(platform)
                .metric(metric)
                .value(value != null ? value : 0.0)
                .recordedAt(LocalDateTime.now())
                .changePercent(0.0) // Requires historical comparison
                .build();
    }
}
