package kz.konturai.parser.service;

import kz.konturai.parser.dto.MarketingAnalysisV3Request;
import kz.konturai.parser.dto.TargetingAIAnalysisResult;
import kz.konturai.parser.dto.targeting.HypothesisCellDto;
import kz.konturai.parser.dto.targeting.HypothesisMatrixDto;
import kz.konturai.parser.dto.targeting.LandingPageAuditDto;
import kz.konturai.parser.dto.targeting.PixelCheckDto;
import kz.konturai.parser.dto.targeting.RiskAnalysisDto;
import kz.konturai.parser.dto.targeting.TargetingOrchestrationDto;
import kz.konturai.parser.dto.targeting.TargetingRecommendationDto;
import kz.konturai.parser.model.MarketingAnalysisV3Document;
import kz.konturai.parser.model.MarketingStrategy;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;

class TargetingCampaignServiceManagementLayerTest {

    private final TargetingCampaignService service =
            new TargetingCampaignService(null, null, null, null, null, null, null, null, null);

    @Test
    void buildAiAnalysisResult_shouldPopulateSummaryFields() throws Exception {
        MarketingStrategy strategy = new MarketingStrategy();
        strategy.setId("strategy-1");
        strategy.setAnalysisId("analysis-1");

        MarketingAnalysisV3Request request = new MarketingAnalysisV3Request();
        request.setBusinessNiche("Автосервис");
        request.setProductName("Oil Change");
        request.setGoal("Лиды");

        MarketingAnalysisV3Document analysis = new MarketingAnalysisV3Document();
        analysis.setRequestData(request);

        List<HypothesisCellDto> cells = new ArrayList<>();
        for (int i = 0; i < 16; i++) {
            cells.add(HypothesisCellDto.builder()
                    .hookIndex(i / 4)
                    .visualIndex(i % 4)
                    .specificAdIdea("Idea " + i)
                    .build());
        }

        List<TargetingOrchestrationDto.AutomationRuleDto> rules = List.of(
                buildRule("rule-1"),
                buildRule("rule-2"),
                buildRule("rule-3"));

        TargetingRecommendationDto recommendation = TargetingRecommendationDto.builder()
                .recommendedType("MIXED")
                .recommendedTypeLabel("Комбинированный")
                .campaignObjective("LEADS")
                .questionnaireSignals(List.of("signal"))
                .typeRationale("reason")
                .quickWins(List.of("win"))
                .warnings(List.of("warning"))
                .pixelHealth(PixelCheckDto.builder().fbp(true).capi(true).gtm(true).build())
                .lpAudit(LandingPageAuditDto.builder().matchScore(88).build())
                .risks(RiskAnalysisDto.builder().policyRiskLevel("High - высокий риск").build())
                .suggestedRules(rules)
                .hypothesisMatrix(HypothesisMatrixDto.builder().matrix(cells).build())
                .build();

        Method method = TargetingCampaignService.class.getDeclaredMethod(
                "buildAiAnalysisResult",
                MarketingStrategy.class,
                MarketingAnalysisV3Document.class,
                TargetingRecommendationDto.class);
        method.setAccessible(true);

        TargetingAIAnalysisResult result = (TargetingAIAnalysisResult) method.invoke(
                service, strategy, analysis, recommendation);

        assertEquals("Strong", result.getTechnicalHealthSummary());
        assertEquals(88, result.getLpMatchScore());
        assertEquals("High - высокий риск", result.getPolicyRiskLevel());
        assertEquals(3, result.getSuggestedAutomationRulesCount());
        assertEquals(16, result.getMatrixCellsCount());
        assertSame(recommendation, result.getTargetingRecommendation());
    }

    private TargetingOrchestrationDto.AutomationRuleDto buildRule(String id) {
        return TargetingOrchestrationDto.AutomationRuleDto.builder()
                .ruleId(id)
                .entityLevel("ADSET")
                .conditionGroup(TargetingOrchestrationDto.ConditionGroup.AND)
                .conditions(List.of(TargetingOrchestrationDto.ConditionDto.builder()
                        .metric("spend")
                        .operator(TargetingOrchestrationDto.Operator.GREATER_THAN)
                        .value(BigDecimal.TEN)
                        .build()))
                .action("PAUSE")
                .actionValue(BigDecimal.ZERO)
                .build();
    }
}
