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

import de.effigenix.domain.inventory.*;
import de.effigenix.infrastructure.inventory.persistence.mapper.StorageLocationMapper;
import de.effigenix.shared.common.RepositoryError;
import de.effigenix.shared.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

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

@Repository
@Profile("!no-db")
@Transactional(readOnly = true)
public class JpaStorageLocationRepository implements StorageLocationRepository {

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

    private final StorageLocationJpaRepository jpaRepository;
    private final StorageLocationMapper mapper;

    public JpaStorageLocationRepository(StorageLocationJpaRepository jpaRepository, StorageLocationMapper mapper) {
        this.jpaRepository = jpaRepository;
        this.mapper = mapper;
    }

    @Override
    public Result<RepositoryError, Optional<StorageLocation>> findById(StorageLocationId id) {
        try {
            Optional<StorageLocation> result = jpaRepository.findById(id.value())
                    .map(mapper::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, List<StorageLocation>> findAll() {
        try {
            List<StorageLocation> result = jpaRepository.findAll().stream()
                    .map(mapper::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
    public Result<RepositoryError, List<StorageLocation>> findByStorageType(StorageType storageType) {
        try {
            List<StorageLocation> result = jpaRepository.findByStorageType(storageType.name()).stream()
                    .map(mapper::toDomain)
                    .collect(Collectors.toList());
            return Result.success(result);
        } catch (Exception e) {
            logger.trace("Database error in findByStorageType", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

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

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

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

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