package com.sikey.wa04.business.infrastructure.adapter.dao;

import com.sikey.wa04.business.domain.adapter.GroupMemberAdapter;
import com.sikey.wa04.business.domain.entity.GroupId;
import com.sikey.wa04.business.domain.entity.GroupMember;
import com.sikey.wa04.business.domain.entity.UserId;
import com.sikey.wa04.business.infrastructure.dto.model.GroupMemberModel;
import com.sikey.wa04.business.infrastructure.repository.GroupMemberRepository;
import com.sikey.wa04.common.enums.GroupMemberRole;
import com.sikey.wa04.common.enums.UserType;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.List;

/**
 * 群组成员适配器
 *
 * @author luoyangwei
 */
@Slf4j
@Component
public class GroupMemberAdapterImpl implements GroupMemberAdapter {

    @Resource
    private GroupMemberRepository groupMemberRepository;

    @Override
    public List<GroupMember> findMembers(GroupId groupId) {
        List<GroupMemberModel> groupMemberModels = groupMemberRepository.findByGroupId(groupId.getId());
        return groupMemberModels.stream().map(model -> new GroupMember()
                .setGroupId(model.getGroupId())
                .setRole(GroupMemberRole.valueOf(model.getRole()))
                .setRefId(model.getRefId())
                .setType(UserType.valueOf(model.getType()))).toList();
    }

    @Override
    public void join(GroupId groupId, GroupMember member) {
        GroupMemberModel groupMemberModel = new GroupMemberModel();
        groupMemberModel.setGroupId(groupId.getId());
        groupMemberModel.setRefId(member.getRefId());
        groupMemberModel.setType(member.getType().getValue());
        groupMemberModel.setRole(member.getRole().getValue());
        groupMemberModel.setCreatedAt(Instant.now());
        groupMemberModel.setUpdatedAt(Instant.now());
        groupMemberRepository.save(groupMemberModel);
    }

    @Override
    public void leave(GroupId groupId, UserId userId) {
        groupMemberRepository.deleteByGroupIdAndRefId(groupId.getId(), userId.getId());
    }

    @Override
    public void deleteByGroupId(String groupId) {
        groupMemberRepository.deleteByGroupId(groupId);
    }
}
