package com.social.media.infrastructure.persistence.mapper;

import com.social.media.domain.socialaccount.aggregate.SocialAccount;
import com.social.media.domain.socialaccount.valueobject.*;
import com.social.media.domain.company.valueobject.CompanyId;
import com.social.media.domain.socialnetwork.valueobject.SocialNetworkId;
import com.social.media.infrastructure.persistence.entity.SocialAccountEntity;
import com.social.media.infrastructure.persistence.entity.SocialAccountStatusEntity;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Mapper between SocialAccount domain aggregate and SocialAccountEntity
 */
@Component
public class SocialAccountEntityMapper {
    
    public SocialAccountEntity toEntity(SocialAccount socialAccount) {
        if (socialAccount == null) {
            return null;
        }
        
        SocialAccountEntity entity = new SocialAccountEntity();
        entity.setId(socialAccount.getId().value());
        entity.setCompanyId(socialAccount.getCompanyId().value());
        entity.setSocialNetworkId(socialAccount.getSocialNetworkId().value());
        entity.setUsername(socialAccount.getUsername());
        entity.setDisplayName(socialAccount.getDisplayName());
        entity.setProfilePhotoUrl(socialAccount.getProfilePhotoUrl());
        entity.setBio(socialAccount.getBio());
        entity.setStatus(mapToEntityStatus(socialAccount.getConnectionStatus()));
        entity.setVerified(socialAccount.isVerified());
        
        // Initialize default metrics as JSONB
        Map<String, Object> metrics = new HashMap<>();
        metrics.put("followers", 0L);
        metrics.put("following", 0L);
        metrics.put("posts", 0L);
        metrics.put("engagement", 0.0);
        metrics.put("avgLikes", 0.0);
        metrics.put("avgComments", 0.0);
        metrics.put("avgShares", 0.0);
        metrics.put("reachRate", 0.0);
        metrics.put("impressionRate", 0.0);
        metrics.put("lastUpdated", null);
        entity.setMetrics(metrics);
        
        // Initialize default tokens as JSONB
        Map<String, Object> tokens = new HashMap<>();
        tokens.put("accessToken", "");
        tokens.put("refreshToken", "");
        tokens.put("tokenType", "Bearer");
        tokens.put("expiresAt", null);
        tokens.put("scope", new String[]{});
        tokens.put("isExpired", true);
        tokens.put("needsRefresh", true);
        entity.setTokens(tokens);
        
        // Initialize default automation config as JSONB
        Map<String, Object> automationConfig = new HashMap<>();
        automationConfig.put("followEnabled", false);
        automationConfig.put("unfollowEnabled", false);
        automationConfig.put("likeEnabled", false);
        automationConfig.put("commentEnabled", false);
        entity.setAutomationConfig(automationConfig);
        
        entity.setLastSyncDate(socialAccount.getLastSyncDate());
        entity.setCreatedAt(socialAccount.getCreatedAt());
        entity.setUpdatedAt(socialAccount.getUpdatedAt());
        entity.setRegistrationDate(socialAccount.getRegistrationDate());
        
        return entity;
    }
    
    public SocialAccount toDomain(SocialAccountEntity entity) {
        if (entity == null) {
            return null;
        }
        
        SocialAccountId id = new SocialAccountId(entity.getId());
        CompanyId companyId = new CompanyId(Long.valueOf(entity.getCompanyId()));
        SocialNetworkId socialNetworkId = new SocialNetworkId(entity.getSocialNetworkId());
        ConnectionStatus connectionStatus = mapToDomainStatus(entity.getStatus());
        
        return SocialAccount.reconstruct(
            id,
            companyId,
            null, // responsibleUserId not mapped
            socialNetworkId,
            entity.getUsername(),
            entity.getDisplayName(),
            entity.getBio(),
            entity.getProfilePhotoUrl(),
            entity.getProfileUrl(),
            null, // metrics not mapped in this simplified version
            entity.getVerified(),
            entity.getIsPrivate(),
            entity.getCategory(),
            entity.getContactPhone(),
            null, // contactEmail needs Email value object conversion
            entity.getLocation(),
            entity.getWebsite(),
            null, // tokens not mapped in this simplified version
            null, // automationConfig not mapped in this simplified version
            connectionStatus,
            entity.getLastSyncDate(),
            entity.getNextSyncDate(),
            entity.getLastSyncError(),
            entity.getActive(),
            entity.getRegistrationDate(),
            entity.getLastUpdateDate(),
            entity.getDeleted(),
            entity.getCreatedAt(),
            entity.getUpdatedAt()
        );
    }
    
    private SocialAccountStatusEntity mapToEntityStatus(ConnectionStatus status) {
        return switch (status) {
            case ACTIVE -> SocialAccountStatusEntity.ACTIVE;
            case INACTIVE -> SocialAccountStatusEntity.INACTIVE;
            case TOKEN_ERROR -> SocialAccountStatusEntity.ERROR;
            case SUSPENDED -> SocialAccountStatusEntity.ERROR;
            case BANNED -> SocialAccountStatusEntity.ERROR;
        };
    }
    
    private ConnectionStatus mapToDomainStatus(SocialAccountStatusEntity status) {
        return switch (status) {
            case ACTIVE -> ConnectionStatus.ACTIVE;
            case INACTIVE -> ConnectionStatus.INACTIVE;
            case ERROR -> ConnectionStatus.TOKEN_ERROR;
            case EXPIRED -> ConnectionStatus.TOKEN_ERROR;
            case PENDING -> ConnectionStatus.INACTIVE;
        };
    }
}
