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

import de.effigenix.domain.masterdata.*;
import de.effigenix.infrastructure.masterdata.persistence.mapper.ArticleMapper;
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 JpaArticleRepository implements ArticleRepository {

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

    private final ArticleJpaRepository jpaRepository;
    private final ArticleMapper mapper;

    public JpaArticleRepository(ArticleJpaRepository jpaRepository, ArticleMapper mapper) {
        this.jpaRepository = jpaRepository;
        this.mapper = mapper;
    }

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

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

    @Override
    @Transactional
    public Result<RepositoryError, Void> save(Article article) {
        try {
            jpaRepository.save(mapper.toEntity(article));
            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(Article article) {
        try {
            jpaRepository.deleteById(article.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> existsByArticleNumber(ArticleNumber articleNumber) {
        try {
            return Result.success(jpaRepository.existsByArticleNumber(articleNumber.value()));
        } catch (Exception e) {
            logger.trace("Database error in existsByArticleNumber", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }
}
