package com.social.media.application.campaign.handler;

import com.social.media.application.campaign.command.CreateAutomationCampaignCommand;
import com.social.media.domain.campaign.aggregate.AutomationCampaign;
import com.social.media.domain.campaign.service.AutomationCampaignDomainService;
import com.social.media.domain.campaign.valueobject.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Collectors;

/**
 * Create Automation Campaign Command Handler
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CreateAutomationCampaignHandler {
    
    private final AutomationCampaignDomainService campaignDomainService;
    
    @Transactional
    public AutomationCampaign handle(CreateAutomationCampaignCommand command) {
        log.info("Creating automation campaign: {}", command.getName());
        
        // Convert command to domain objects
        CampaignType campaignType = CampaignType.valueOf(command.getCampaignType());
        TargetConfiguration targetConfig = buildTargetConfiguration(command);
        ActionConfiguration actionConfig = buildActionConfiguration(command);
        ScheduleConfiguration scheduleConfig = buildScheduleConfiguration(command);
        
        // Create campaign via domain service
        AutomationCampaign campaign = campaignDomainService.createCampaign(
                command.getCompanyId(),
                command.getSocialAccountId(),
                command.getName(),
                command.getDescription(),
                campaignType,
                targetConfig,
                actionConfig,
                scheduleConfig
        );
        
        log.info("Automation campaign created successfully: {}", campaign.getId().getValue());
        return campaign;
    }
    
    private TargetConfiguration buildTargetConfiguration(CreateAutomationCampaignCommand command) {
        TargetConfiguration.FilterCriteria filterCriteria = null;
        
        if (command.getFilterCriteria() != null) {
            filterCriteria = new TargetConfiguration.FilterCriteria(
                    command.getFilterCriteria().getMinFollowers(),
                    command.getFilterCriteria().getMaxFollowers(),
                    command.getFilterCriteria().getAccountAge(),
                    command.getFilterCriteria().getEngagementRate()
            );
        }
        
        return new TargetConfiguration(
                command.getTargetUsers() != null ? command.getTargetUsers() : java.util.List.of(),
                command.getTargetHashtags() != null ? command.getTargetHashtags() : java.util.List.of(),
                command.getTargetLocations() != null ? command.getTargetLocations() : java.util.List.of(),
                command.getExcludeUsers() != null ? command.getExcludeUsers() : java.util.List.of(),
                filterCriteria != null ? filterCriteria : new TargetConfiguration.FilterCriteria(0, null, null, null)
        );
    }
    
    private ActionConfiguration buildActionConfiguration(CreateAutomationCampaignCommand command) {
        java.util.List<ActionType> actionTypes = java.util.List.of();
        
        if (command.getActions() != null) {
            actionTypes = command.getActions().stream()
                    .map(ActionType::valueOf)
                    .collect(Collectors.toList());
        }
        
        ActionConfiguration.ActionSequence actionSequence = ActionConfiguration.ActionSequence.RANDOM;
        if (command.getActionSequence() != null) {
            actionSequence = ActionConfiguration.ActionSequence.valueOf(command.getActionSequence());
        }
        
        return new ActionConfiguration(
                actionTypes,
                actionSequence,
                command.getActionsPerUser() != null ? command.getActionsPerUser() : 1,
                command.getCommentTemplates() != null ? command.getCommentTemplates() : java.util.List.of(),
                command.getDmTemplates() != null ? command.getDmTemplates() : java.util.List.of(),
                command.getCustomMessages() != null ? command.getCustomMessages() : java.util.List.of()
        );
    }
    
    private ScheduleConfiguration buildScheduleConfiguration(CreateAutomationCampaignCommand command) {
        ScheduleConfiguration.WorkingHours workingHours = null;
        
        if (command.getWorkingHours() != null) {
            workingHours = new ScheduleConfiguration.WorkingHours(
                    command.getWorkingHours().getEnabled(),
                    command.getWorkingHours().getStart(),
                    command.getWorkingHours().getEnd(),
                    command.getWorkingHours().getWorkDays()
            );
        }
        
        ScheduleConfiguration.Randomization randomization = null;
        
        if (command.getRandomization() != null) {
            randomization = new ScheduleConfiguration.Randomization(
                    command.getRandomization().getEnabled(),
                    command.getRandomization().getMinDelay(),
                    command.getRandomization().getMaxDelay()
            );
        }
        
        return new ScheduleConfiguration(
                command.getStartDate(),
                command.getEndDate(),
                command.getDailyLimit() != null ? command.getDailyLimit() : 100,
                command.getHourlyLimit() != null ? command.getHourlyLimit() : 10,
                command.getActionsPerHour() != null ? command.getActionsPerHour() : 5,
                command.getDelayBetweenActions() != null ? command.getDelayBetweenActions() : 60,
                workingHours != null ? workingHours : 
                    new ScheduleConfiguration.WorkingHours(true, 
                        java.time.LocalTime.of(9, 0), 
                        java.time.LocalTime.of(18, 0), 
                        java.util.List.of(1, 2, 3, 4, 5)),
                randomization != null ? randomization :
                    new ScheduleConfiguration.Randomization(true, 30, 180)
        );
    }
}
