package com.social.media.infrastructure.persistence.mapper;

import com.social.media.domain.socialnetwork.aggregate.SocialNetwork;
import com.social.media.domain.socialnetwork.valueobject.*;
import com.social.media.infrastructure.persistence.entity.SocialNetworkEntity;
import com.social.media.infrastructure.persistence.entity.SocialNetworkStatusEntity;
import com.social.media.infrastructure.persistence.entity.SocialNetworkTypeEntity;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Mapper between SocialNetwork domain aggregate and SocialNetworkEntity
 */
@Component
public class SocialNetworkEntityMapper {
    
    public SocialNetworkEntity toEntity(SocialNetwork socialNetwork) {
        if (socialNetwork == null) {
            return null;
        }
        
        SocialNetworkEntity entity = new SocialNetworkEntity();
        entity.setId(socialNetwork.getId().value());
        entity.setName(socialNetwork.getDisplayName());
        entity.setType(mapToEntityType(socialNetwork.getPlatformType()));
        entity.setBaseUrl(socialNetwork.getBaseUrl());
        entity.setLogoUrl(socialNetwork.getLogoUrl());
        entity.setStatus(mapToEntityStatus(socialNetwork.isActive()));
        
        // Map capabilities
        if (socialNetwork.getCapabilities() != null) {
            PlatformCapabilities capabilities = socialNetwork.getCapabilities();
            entity.setSupportsScheduling(capabilities.supportsPosts());
            entity.setSupportsAnalytics(true); // Default to true for analytics
            entity.setSupportsHashtags(true); // Default to true for hashtags
            entity.setMaxPostLength(capabilities.characterLimitPost());
            entity.setMaxHashtags(30); // Default max hashtags
            entity.setSupportsImages(capabilities.supportsMediaFormat("image"));
            entity.setSupportsVideos(capabilities.supportsVideos());
            entity.setMaxImageSizeMb(10); // Default 10MB
            entity.setMaxVideoSizeMb(100); // Default 100MB
        } else {
            // Set defaults if no capabilities
            entity.setSupportsScheduling(true);
            entity.setSupportsAnalytics(true);
            entity.setSupportsHashtags(true);
            entity.setMaxPostLength(280);
            entity.setMaxHashtags(30);
            entity.setSupportsImages(true);
            entity.setSupportsVideos(true);
            entity.setMaxImageSizeMb(10);
            entity.setMaxVideoSizeMb(100);
        }
        
        // Map API configuration
        if (socialNetwork.getApiConfiguration() != null) {
            ApiConfiguration config = socialNetwork.getApiConfiguration();
            entity.setApiUrl(config.apiEndpoint());
            entity.setOauthClientId(config.getConfiguration("clientId"));
            entity.setOauthClientSecret(config.getConfiguration("clientSecret"));
            entity.setOauthRedirectUrl(config.getConfiguration("redirectUrl"));
            entity.setOauthScope(config.getConfiguration("scope"));
        }
        
        entity.setCreatedAt(socialNetwork.getCreatedAt());
        entity.setUpdatedAt(socialNetwork.getUpdatedAt());
        
        return entity;
    }
    
    public SocialNetwork toDomain(SocialNetworkEntity entity) {
        if (entity == null) {
            return null;
        }
        
        SocialNetworkId id = SocialNetworkId.of(entity.getId());
        PlatformType platformType = mapToDomainType(entity.getType());
        
        // Create capabilities
        PlatformCapabilities capabilities = new PlatformCapabilities(
            entity.getSupportsScheduling(),
            false, // stories - not mapped
            entity.getSupportsVideos(),
            false, // reels - not mapped
            false, // live - not mapped
            false, // direct messages - not mapped
            entity.getMaxPostLength(),
            500, // default bio limit
            List.of("image/jpeg", "image/png", "video/mp4") // default formats
        );
        
        // Create API configuration
        ApiConfiguration apiConfig = new ApiConfiguration(
            entity.getApiUrl(),
            "v1", // default version
            Map.of(
                "clientId", entity.getOauthClientId() != null ? entity.getOauthClientId() : "",
                "clientSecret", entity.getOauthClientSecret() != null ? entity.getOauthClientSecret() : "",
                "redirectUrl", entity.getOauthRedirectUrl() != null ? entity.getOauthRedirectUrl() : "",
                "scope", entity.getOauthScope() != null ? entity.getOauthScope() : ""
            ),
            1000 // default rate limit
        );
        
        return SocialNetwork.reconstruct(
            id,
            platformType,
            entity.getName(),
            entity.getBaseUrl(),
            entity.getLogoUrl(),
            "#1DA1F2", // default primary color
            capabilities,
            apiConfig,
            mapToDomainStatus(entity.getStatus()),
            entity.getCreatedAt(),
            false, // deleted not mapped
            entity.getCreatedAt(),
            entity.getUpdatedAt()
        );
    }
    
    private SocialNetworkTypeEntity mapToEntityType(PlatformType type) {
        return switch (type) {
            case INSTAGRAM -> SocialNetworkTypeEntity.INSTAGRAM;
            case FACEBOOK -> SocialNetworkTypeEntity.FACEBOOK;
            case TWITTER -> SocialNetworkTypeEntity.TWITTER;
            case LINKEDIN -> SocialNetworkTypeEntity.LINKEDIN;
            case YOUTUBE -> SocialNetworkTypeEntity.YOUTUBE;
            case TIKTOK -> SocialNetworkTypeEntity.TIKTOK;
        };
    }
    
    private PlatformType mapToDomainType(SocialNetworkTypeEntity type) {
        return switch (type) {
            case INSTAGRAM -> PlatformType.INSTAGRAM;
            case FACEBOOK -> PlatformType.FACEBOOK;
            case TWITTER -> PlatformType.TWITTER;
            case LINKEDIN -> PlatformType.LINKEDIN;
            case YOUTUBE -> PlatformType.YOUTUBE;
            case TIKTOK -> PlatformType.TIKTOK;
            case THREADS -> PlatformType.TWITTER; // Map THREADS to TWITTER as fallback
        };
    }
    
    private SocialNetworkStatusEntity mapToEntityStatus(boolean isActive) {
        return isActive ? SocialNetworkStatusEntity.ACTIVE : SocialNetworkStatusEntity.INACTIVE;
    }
    
    private boolean mapToDomainStatus(SocialNetworkStatusEntity status) {
        return status == SocialNetworkStatusEntity.ACTIVE;
    }
}
