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

import de.effigenix.domain.production.ProductionOrder;
import de.effigenix.domain.production.ProductionOrderId;
import de.effigenix.domain.production.ProductionOrderRepository;
import de.effigenix.infrastructure.production.persistence.mapper.ProductionOrderMapper;
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.orm.ObjectOptimisticLockingFailureException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

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

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

    private final ProductionOrderJpaRepository jpaRepository;
    private final ProductionOrderMapper mapper;

    public JpaProductionOrderRepository(ProductionOrderJpaRepository jpaRepository, ProductionOrderMapper mapper) {
        this.jpaRepository = jpaRepository;
        this.mapper = mapper;
    }

    @Override
    public Result<RepositoryError, Optional<ProductionOrder>> findById(ProductionOrderId id) {
        try {
            Optional<ProductionOrder> 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<ProductionOrder>> findAll() {
        try {
            List<ProductionOrder> result = jpaRepository.findAll().stream()
                    .map(mapper::toDomain)
                    .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(ProductionOrder order) {
        try {
            var existing = jpaRepository.findById(order.id().value());
            if (existing.isPresent()) {
                mapper.updateEntity(existing.get(), order);
            } else {
                jpaRepository.save(mapper.toEntity(order));
            }
            return Result.success(null);
        } catch (ObjectOptimisticLockingFailureException e) {
            logger.warn("Optimistic locking failure for production order {}", order.id().value());
            return Result.failure(new RepositoryError.ConcurrentModification(
                    "Production order was modified by another transaction"));
        } catch (Exception e) {
            logger.trace("Database error in save", e);
            return Result.failure(new RepositoryError.DatabaseError(e.getMessage()));
        }
    }
}
