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

import de.effigenix.domain.masterdata.*;
import de.effigenix.infrastructure.masterdata.persistence.mapper.SupplierMapper;
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 JpaSupplierRepository implements SupplierRepository {

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

    private final SupplierJpaRepository jpaRepository;
    private final SupplierMapper mapper;

    public JpaSupplierRepository(SupplierJpaRepository jpaRepository, SupplierMapper mapper) {
        this.jpaRepository = jpaRepository;
        this.mapper = mapper;
    }

    @Override
    public Result<RepositoryError, Optional<Supplier>> findById(SupplierId id) {
        try {
            Optional<Supplier> 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<Supplier>> findAll() {
        try {
            List<Supplier> 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<Supplier>> findByStatus(SupplierStatus status) {
        try {
            List<Supplier> 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(Supplier supplier) {
        try {
            jpaRepository.save(mapper.toEntity(supplier));
            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(Supplier supplier) {
        try {
            jpaRepository.deleteById(supplier.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> existsByName(SupplierName 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()));
        }
    }
}
