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

import de.effigenix.domain.production.*;
import de.effigenix.infrastructure.production.persistence.mapper.RecipeMapper;
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 JpaRecipeRepository implements RecipeRepository {

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

    private final RecipeJpaRepository jpaRepository;
    private final RecipeMapper mapper;

    public JpaRecipeRepository(RecipeJpaRepository jpaRepository, RecipeMapper mapper) {
        this.jpaRepository = jpaRepository;
        this.mapper = mapper;
    }

    @Override
    public Result<RepositoryError, Optional<Recipe>> findById(RecipeId id) {
        try {
            Optional<Recipe> 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<Recipe>> findAll() {
        try {
            List<Recipe> 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
    @Transactional
    public Result<RepositoryError, Void> save(Recipe recipe) {
        try {
            jpaRepository.save(mapper.toEntity(recipe));
            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(Recipe recipe) {
        try {
            jpaRepository.deleteById(recipe.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, List<Recipe>> findByStatus(RecipeStatus status) {
        try {
            List<Recipe> 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
    public Result<RepositoryError, List<Recipe>> findByArticleId(String articleId) {
        try {
            List<Recipe> result = jpaRepository.findByArticleId(articleId).stream()
                    .map(mapper::toDomain)
                    .collect(Collectors.toList());
            return Result.success(result);
        } catch (Exception e) {
            logger.trace("Database error in findByArticleId", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }

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