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.repository.AutomationCampaignRepository;
import com.social.media.domain.campaign.valueobject.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * Handler for creating automation campaigns
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class CreateAutomationCampaignHandler {
    
    private final AutomationCampaignRepository campaignRepository;
    
    public AutomationCampaign handle(CreateAutomationCampaignCommand command) {
        log.info("Creating automation campaign: {}", command.getName());
        
        // Generate unique campaign code
        String campaignCode = generateCampaignCode();
        
        // Build target configuration
        TargetConfiguration.FilterCriteria filterCriteria = TargetConfiguration.FilterCriteria.builder()
                .minFollowers(command.getMinFollowers())
                .maxFollowers(command.getMaxFollowers())
                .accountAge(command.getAccountAge())
                .engagementRate(command.getEngagementRate())
                .build();
        
        TargetConfiguration targetConfig = TargetConfiguration.builder()
                .targetUsers(command.getTargetUsers() != null ? command.getTargetUsers() : List.of())
                .targetHashtags(command.getTargetHashtags() != null ? command.getTargetHashtags() : List.of())
                .targetLocations(command.getTargetLocations() != null ? command.getTargetLocations() : List.of())
                .excludeUsers(command.getExcludeUsers() != null ? command.getExcludeUsers() : List.of())
                .filterCriteria(filterCriteria)
                .build();
        
        // Build action configuration
        List<ActionType> allowedActions = command.getActions() != null ? 
                command.getActions().stream()
                        .map(ActionType::valueOf)
                        .collect(Collectors.toList()) : List.of();
        
        ActionConfiguration.ActionSequence actionSequence = ActionConfiguration.ActionSequence.builder()
                .sequence(allowedActions)
                .delayBetweenActions(command.getDelayBetweenActions())
                .randomOrder(false)
                .build();
        
        ActionConfiguration actionConfig = ActionConfiguration.builder()
                .allowedActions(allowedActions)
                .actionSequence(actionSequence)
                .actionsPerUser(command.getActionsPerUser())
                .commentTemplates(command.getCommentTemplates() != null ? command.getCommentTemplates() : List.of())
                .dmTemplates(command.getDmTemplates() != null ? command.getDmTemplates() : List.of())
                .customMessages(command.getCustomMessages() != null ? command.getCustomMessages() : List.of())
                .build();
        
        // Build schedule configuration
        ScheduleConfiguration.WorkingHours workingHours = ScheduleConfiguration.WorkingHours.builder()
                .enabled(false)
                .build();
        
        ScheduleConfiguration.Randomization randomization = ScheduleConfiguration.Randomization.builder()
                .enabled(false)
                .build();
        
        ScheduleConfiguration scheduleConfig = ScheduleConfiguration.builder()
                .startDate(command.getStartDate())
                .endDate(command.getEndDate())
                .dailyLimit(command.getDailyLimit())
                .hourlyLimit(command.getHourlyLimit())
                .actionsPerHour(command.getActionsPerHour())
                .delayBetweenActions(command.getDelayBetweenActions())
                .workingHours(workingHours)
                .randomization(randomization)
                .build();
        
        // Create the campaign
        AutomationCampaign campaign = AutomationCampaign.builder()
                .campaignCode(campaignCode)
                .companyId(command.getCompanyId())
                .socialAccountId(command.getSocialAccountId())
                .name(command.getName())
                .description(command.getDescription())
                .type(CampaignType.valueOf(command.getCampaignType()))
                .status(CampaignStatus.DRAFT)
                .targetConfig(targetConfig)
                .actionConfig(actionConfig)
                .scheduleConfig(scheduleConfig)
                .totalPlannedActions(0)
                .totalExecutedActions(0)
                .successfulActions(0)
                .failedActions(0)
                .isActive(true)
                .autoRestart(false)
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .build();
        
        // Save and return
        AutomationCampaign savedCampaign = campaignRepository.save(campaign);
        
        log.info("Created automation campaign with code: {}", campaignCode);
        return savedCampaign;
    }
    
    private String generateCampaignCode() {
        return "CAM-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }
}
