package com.social.media.mapper;

import com.social.media.domain.entity.User;
import com.social.media.dto.UserDto;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;

@Component
public class UserMapper {
    
    public UserDto toDto(User user) {
        if (user == null) {
            return null;
        }
        
        UserDto dto = new UserDto();
        dto.setId(user.getId());
        dto.setUserCode(user.getUserCode());
        dto.setCompanyId(user.getCompanyId());
        dto.setParentUserId(user.getParentUserId());
        dto.setName(user.getName());
        dto.setEmail(user.getEmail());
        dto.setCpf(user.getCpf());
        dto.setPhone(user.getPhone());
        dto.setAvatarUrl(user.getAvatarUrl());
        dto.setPosition(user.getPosition());
        dto.setDepartment(user.getDepartment());
        dto.setType(user.getType() != null ? user.getType().name() : null);
        dto.setStatus(user.getStatus() != null ? user.getStatus().name() : null);
        dto.setConfiguration(user.getConfiguration());
        dto.setWhatsappEnabled(user.getWhatsappEnabled());
        dto.setProfileVerified(user.getProfileVerified());
        dto.setManagerId(user.getManagerId());
        dto.setOrganizationalLevel(user.getOrganizationalLevel());
        dto.setTimezone(user.getTimezone());
        dto.setLanguage(user.getLanguage());
        dto.setRegistrationDate(user.getRegistrationDate());
        dto.setLastAccessDate(user.getLastAccessDate());
        dto.setDeleted(user.getDeleted());
        dto.setCreatedAt(user.getCreatedAt());
        dto.setUpdatedAt(user.getUpdatedAt());
        
        return dto;
    }
    
    public User toEntity(UserDto dto) {
        if (dto == null) {
            return null;
        }
        
        User user = new User();
        user.setId(dto.getId());
        user.setUserCode(dto.getUserCode());
        user.setCompanyId(dto.getCompanyId());
        user.setParentUserId(dto.getParentUserId());
        user.setName(dto.getName());
        user.setEmail(dto.getEmail());
        user.setCpf(dto.getCpf());
        user.setPhone(dto.getPhone());
        user.setAvatarUrl(dto.getAvatarUrl());
        user.setPosition(dto.getPosition());
        user.setDepartment(dto.getDepartment());
        
        // Convert string to enum
        if (dto.getType() != null) {
            try {
                user.setType(User.UserType.valueOf(dto.getType()));
            } catch (IllegalArgumentException e) {
                user.setType(User.UserType.USER);
            }
        }
        
        if (dto.getStatus() != null) {
            try {
                user.setStatus(User.UserStatus.valueOf(dto.getStatus()));
            } catch (IllegalArgumentException e) {
                user.setStatus(User.UserStatus.PENDING_VERIFICATION);
            }
        }
        
        user.setConfiguration(dto.getConfiguration());
        user.setWhatsappEnabled(dto.getWhatsappEnabled());
        user.setProfileVerified(dto.getProfileVerified());
        user.setManagerId(dto.getManagerId());
        user.setOrganizationalLevel(dto.getOrganizationalLevel());
        user.setTimezone(dto.getTimezone());
        user.setLanguage(dto.getLanguage());
        user.setRegistrationDate(dto.getRegistrationDate());
        user.setLastAccessDate(dto.getLastAccessDate());
        user.setDeleted(dto.getDeleted());
        user.setCreatedAt(dto.getCreatedAt());
        user.setUpdatedAt(dto.getUpdatedAt());
        
        return user;
    }
    
    public User toEntity(UserDto dto, User existingUser) {
        if (dto == null) {
            return existingUser;
        }
        
        if (existingUser == null) {
            return toEntity(dto);
        }
        
        // Atualiza apenas os campos que podem ser modificados
        // ID, userCode, companyId não devem ser modificados após criação
        if (dto.getParentUserId() != null) {
            existingUser.setParentUserId(dto.getParentUserId());
        }
        if (dto.getName() != null) {
            existingUser.setName(dto.getName());
        }
        if (dto.getEmail() != null) {
            existingUser.setEmail(dto.getEmail());
        }
        if (dto.getCpf() != null) {
            existingUser.setCpf(dto.getCpf());
        }
        if (dto.getPhone() != null) {
            existingUser.setPhone(dto.getPhone());
        }
        if (dto.getAvatarUrl() != null) {
            existingUser.setAvatarUrl(dto.getAvatarUrl());
        }
        if (dto.getPosition() != null) {
            existingUser.setPosition(dto.getPosition());
        }
        if (dto.getDepartment() != null) {
            existingUser.setDepartment(dto.getDepartment());
        }
        if (dto.getType() != null) {
            try {
                existingUser.setType(User.UserType.valueOf(dto.getType()));
            } catch (IllegalArgumentException e) {
                // Mantém o valor atual se inválido
            }
        }
        if (dto.getStatus() != null) {
            try {
                existingUser.setStatus(User.UserStatus.valueOf(dto.getStatus()));
            } catch (IllegalArgumentException e) {
                // Mantém o valor atual se inválido
            }
        }
        if (dto.getConfiguration() != null) {
            existingUser.setConfiguration(dto.getConfiguration());
        }
        if (dto.getWhatsappEnabled() != null) {
            existingUser.setWhatsappEnabled(dto.getWhatsappEnabled());
        }
        if (dto.getProfileVerified() != null) {
            existingUser.setProfileVerified(dto.getProfileVerified());
        }
        if (dto.getManagerId() != null) {
            existingUser.setManagerId(dto.getManagerId());
        }
        if (dto.getOrganizationalLevel() != null) {
            existingUser.setOrganizationalLevel(dto.getOrganizationalLevel());
        }
        if (dto.getTimezone() != null) {
            existingUser.setTimezone(dto.getTimezone());
        }
        if (dto.getLanguage() != null) {
            existingUser.setLanguage(dto.getLanguage());
        }
        if (dto.getLastAccessDate() != null) {
            existingUser.setLastAccessDate(dto.getLastAccessDate());
        }
        if (dto.getDeleted() != null) {
            existingUser.setDeleted(dto.getDeleted());
        }
        
        existingUser.setUpdatedAt(LocalDateTime.now());
        
        return existingUser;
    }
    
    public User createEntity(UserDto dto) {
        if (dto == null) {
            return null;
        }
        
        User user = new User();
        user.setCompanyId(dto.getCompanyId());
        user.setParentUserId(dto.getParentUserId());
        user.setName(dto.getName());
        user.setEmail(dto.getEmail());
        user.setCpf(dto.getCpf());
        user.setPhone(dto.getPhone());
        user.setAvatarUrl(dto.getAvatarUrl());
        user.setPosition(dto.getPosition());
        user.setDepartment(dto.getDepartment());
        
        // Set default values if not provided
        if (dto.getType() != null) {
            try {
                user.setType(User.UserType.valueOf(dto.getType()));
            } catch (IllegalArgumentException e) {
                user.setType(User.UserType.USER);
            }
        } else {
            user.setType(User.UserType.USER);
        }
        
        if (dto.getStatus() != null) {
            try {
                user.setStatus(User.UserStatus.valueOf(dto.getStatus()));
            } catch (IllegalArgumentException e) {
                user.setStatus(User.UserStatus.PENDING_VERIFICATION);
            }
        } else {
            user.setStatus(User.UserStatus.PENDING_VERIFICATION);
        }
        
        user.setConfiguration(dto.getConfiguration() != null ? dto.getConfiguration() : new HashMap<>());
        user.setWhatsappEnabled(dto.getWhatsappEnabled() != null ? dto.getWhatsappEnabled() : false);
        user.setProfileVerified(dto.getProfileVerified() != null ? dto.getProfileVerified() : false);
        user.setManagerId(dto.getManagerId());
        user.setOrganizationalLevel(dto.getOrganizationalLevel() != null ? dto.getOrganizationalLevel() : 0);
        user.setTimezone(dto.getTimezone() != null ? dto.getTimezone() : "America/Sao_Paulo");
        user.setLanguage(dto.getLanguage() != null ? dto.getLanguage() : "pt-BR");
        user.setDeleted(dto.getDeleted() != null ? dto.getDeleted() : false);
        
        LocalDateTime now = LocalDateTime.now();
        user.setRegistrationDate(now);
        user.setCreatedAt(now);
        user.setUpdatedAt(now);
        
        return user;
    }
}
