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

import de.effigenix.domain.inventory.*;
import de.effigenix.domain.masterdata.ArticleId;
import de.effigenix.infrastructure.inventory.persistence.mapper.StockMovementMapper;
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.time.Instant;
import java.util.List;
import java.util.Optional;

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

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

    private final StockMovementJpaRepository jpaRepository;
    private final StockMovementMapper mapper;

    public JpaStockMovementRepository(StockMovementJpaRepository jpaRepository, StockMovementMapper mapper) {
        this.jpaRepository = jpaRepository;
        this.mapper = mapper;
    }

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

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

    @Override
    public Result<RepositoryError, List<StockMovement>> findAllByStockId(StockId stockId) {
        try {
            List<StockMovement> result = jpaRepository.findAllByStockId(stockId.value()).stream()
                    .map(mapper::toDomain)
                    .toList();
            return Result.success(result);
        } catch (Exception e) {
            logger.warn("Database error in findAllByStockId", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

    @Override
    public Result<RepositoryError, List<StockMovement>> findAllByArticleId(ArticleId articleId) {
        try {
            List<StockMovement> result = jpaRepository.findAllByArticleId(articleId.value()).stream()
                    .map(mapper::toDomain)
                    .toList();
            return Result.success(result);
        } catch (Exception e) {
            logger.warn("Database error in findAllByArticleId", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

    @Override
    public Result<RepositoryError, List<StockMovement>> findAllByMovementType(MovementType movementType) {
        try {
            List<StockMovement> result = jpaRepository.findAllByMovementType(movementType.name()).stream()
                    .map(mapper::toDomain)
                    .toList();
            return Result.success(result);
        } catch (Exception e) {
            logger.warn("Database error in findAllByMovementType", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

    @Override
    public Result<RepositoryError, List<StockMovement>> findAllByBatchId(String batchId) {
        try {
            List<StockMovement> result = jpaRepository.findAllByBatchId(batchId).stream()
                    .map(mapper::toDomain)
                    .toList();
            return Result.success(result);
        } catch (Exception e) {
            logger.warn("Database error in findAllByBatchId", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

    @Override
    public Result<RepositoryError, List<StockMovement>> findAllByPerformedAtBetween(Instant from, Instant to) {
        try {
            List<StockMovement> result = jpaRepository.findAllByPerformedAtBetween(from, to).stream()
                    .map(mapper::toDomain)
                    .toList();
            return Result.success(result);
        } catch (Exception e) {
            logger.warn("Database error in findAllByPerformedAtBetween", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

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