package com.bio.bio_backend.domain.base.resource.service;

import com.bio.bio_backend.domain.base.resource.dto.ResourceDto;
import com.bio.bio_backend.domain.base.resource.entity.Resource;
import com.bio.bio_backend.domain.base.resource.repository.ResourceRepository;
import com.bio.bio_backend.domain.base.resource.mapper.ResourceMapper;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Slf4j
@Transactional(readOnly = true)
public class ResourceServiceImpl implements ResourceService {

    private final ResourceRepository repository;
    private final ResourceMapper mapper;

    @Override
    @Transactional
    public ResourceDto createResource(ResourceDto dto) {
        try {
            Resource entity = mapper.toEntity(dto);
            return mapper.toDto(repository.save(entity));
        } catch (Exception e) {
            return null;
        }
    }

    @Transactional
    @Override
    public List<ResourceDto> createResourceList(List<ResourceDto> list) {

        List<ResourceDto> resultList = new ArrayList<>();

        for (ResourceDto dto : list) {
            try {
                Resource entity = mapper.toEntity(dto);
                resultList.add(mapper.toDto(repository.save(entity)));
            } catch (Exception e) {
                ResourceDto resultDto = null;
                resultList.add(resultDto);
            }
        }

        return resultList;
    }

    @Override
    public ResourceDto getById(Long id) {
        return repository.findById(id).map(mapper::toDto).orElse(null);
    }

    @Override
    public List<ResourceDto> getAll() {
        return repository.findAll().stream().map(mapper::toDto).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public ResourceDto update(Long id, ResourceDto dto) {
        Resource entity = repository.findById(id).orElseThrow();
        // TODO: update fields
        return mapper.toDto(repository.save(entity));
    }

    @Override
    @Transactional
    public void delete(Long id) {
        repository.deleteById(id);
    }

}
