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

import com.bio.bio_backend.domain.base.authgroupresource.dto.AuthGroupResourceDto;
import com.bio.bio_backend.domain.base.authgroupresource.entity.AuthGroupResource;
import com.bio.bio_backend.domain.base.authgroupresource.repository.AuthGroupResourceRepository;
import com.bio.bio_backend.domain.base.authgroupresource.mapper.AuthGroupResourceMapper;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
import com.bio.bio_backend.domain.base.resource.entity.Resource;

@Service
@RequiredArgsConstructor
@Slf4j
@Transactional(readOnly = true)
public class AuthGroupResourceServiceImpl implements AuthGroupResourceService {

    private final AuthGroupResourceRepository repository;
    private final AuthGroupResourceMapper mapper;

    @Override
    @Transactional
    public AuthGroupResourceDto create(AuthGroupResourceDto dto) {
        AuthGroupResource entity = mapper.toEntity(dto);
        return mapper.toDto(repository.save(entity));
    }

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

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

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

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

    @Override
    @Transactional
    public void replaceAuthGroupResources(Long authGroupOid, List<Long> resourceOids) {
        repository.deleteByAuthGroupOid(authGroupOid);

        if (resourceOids == null || resourceOids.isEmpty()) {
            return;
        }

        AuthGroup groupRef = new AuthGroup();
        groupRef.setOid(authGroupOid);

        for (Long resourceOid : resourceOids) {
            Resource resourceRef = new Resource();
            resourceRef.setOid(resourceOid);

            AuthGroupResource entity = AuthGroupResource.builder()
                    .authGroupOid(groupRef)
                    .resourceOid(resourceRef)
                    .build();
            repository.save(entity);
        }
    }
}
