package de.effigenix.infrastructure.usermanagement.persistence.repository;

import de.effigenix.shared.common.RepositoryError;
import de.effigenix.domain.usermanagement.Role;
import de.effigenix.domain.usermanagement.RoleId;
import de.effigenix.domain.usermanagement.RoleName;
import de.effigenix.domain.usermanagement.RoleRepository;
import de.effigenix.infrastructure.usermanagement.persistence.mapper.RoleMapper;
import de.effigenix.shared.common.Result;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * JPA Adapter for RoleRepository (Domain Interface).
 * Infrastructure Layer - implements the Domain's RoleRepository interface.
 *
 * This is the Adapter pattern in Hexagonal Architecture:
 * - Domain defines the interface (RoleRepository)
 * - Infrastructure implements it (JpaRoleRepository)
 * - Uses Spring Data JPA (RoleJpaRepository) internally
 * - Translates between Domain and JPA entities using RoleMapper
 *
 * @Transactional ensures database consistency.
 */
@Repository
@Profile("!no-db")
@Transactional(readOnly = true)
public class JpaRoleRepository implements RoleRepository {

    private static final Logger logger = LoggerFactory.getLogger(JpaRoleRepository.class);

    private final RoleJpaRepository jpaRepository;
    private final RoleMapper roleMapper;

    public JpaRoleRepository(RoleJpaRepository jpaRepository, RoleMapper roleMapper) {
        this.jpaRepository = jpaRepository;
        this.roleMapper = roleMapper;
    }

    @Override
    public Result<RepositoryError, Optional<Role>> findById(RoleId id) {
        try {
            Optional<Role> result = jpaRepository.findById(id.value())
                    .map(roleMapper::toDomain);
            return Result.success(result);
        } catch (Exception e) {
            logger.trace("Database error in findById", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

    @Override
    public Result<RepositoryError, Optional<Role>> findByName(RoleName name) {
        try {
            Optional<Role> result = jpaRepository.findByName(name)
                    .map(roleMapper::toDomain);
            return Result.success(result);
        } catch (Exception e) {
            logger.trace("Database error in findByName", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

    @Override
    public Result<RepositoryError, List<Role>> findAll() {
        try {
            List<Role> result = jpaRepository.findAll().stream()
                    .map(roleMapper::toDomain)
                    .collect(Collectors.toList());
            return Result.success(result);
        } catch (Exception e) {
            logger.trace("Database error in findAll", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

    @Override
    @Transactional
    public Result<RepositoryError, Void> save(Role role) {
        try {
            jpaRepository.save(roleMapper.toEntity(role));
            return Result.success(null);
        } catch (Exception e) {
            logger.trace("Database error in save", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

    @Override
    @Transactional
    public Result<RepositoryError, Void> delete(Role role) {
        try {
            jpaRepository.deleteById(role.id().value());
            return Result.success(null);
        } catch (Exception e) {
            logger.trace("Database error in delete", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

    @Override
    public Result<RepositoryError, Boolean> existsByName(RoleName name) {
        try {
            return Result.success(jpaRepository.existsByName(name));
        } catch (Exception e) {
            logger.trace("Database error in existsByName", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }
}
