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

import com.bio.bio_backend.domain.base.memberauthgroup.dto.MemberAuthGroupDto;
import com.bio.bio_backend.domain.base.memberauthgroup.entity.MemberAuthGroup;
import com.bio.bio_backend.domain.base.memberauthgroup.repository.MemberAuthGroupRepository;
import com.bio.bio_backend.domain.base.memberauthgroup.mapper.MemberAuthGroupMapper;
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.member.entity.Member;

@Service
@RequiredArgsConstructor
@Slf4j
@Transactional(readOnly = true)
public class MemberAuthGroupServiceImpl implements MemberAuthGroupService {

    private final MemberAuthGroupRepository repository;
    private final MemberAuthGroupMapper mapper;

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

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

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

    @Override
    @Transactional
    public MemberAuthGroupDto update(Long id, MemberAuthGroupDto dto) {
        MemberAuthGroup 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 replaceMemberAuthGroups(Long memberOid, List<Long> authGroupOids) {
        repository.deleteByMemberOid(memberOid);

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

        Member memberRef = new Member();
        memberRef.setOid(memberOid);

        for (Long groupOid : authGroupOids) {
            AuthGroup groupRef = new AuthGroup();
            groupRef.setOid(groupOid);

            MemberAuthGroup entity = MemberAuthGroup.builder()
                    .memberOid(memberRef)
                    .authGroupOid(groupRef)
                    .build();
            repository.save(entity);
        }
    }
}
