package com.unicorn.hgzero.meeting.infra.gateway;

import com.unicorn.hgzero.meeting.biz.domain.Session;
import com.unicorn.hgzero.meeting.biz.usecase.out.SessionReader;
import com.unicorn.hgzero.meeting.biz.usecase.out.SessionWriter;
import com.unicorn.hgzero.meeting.infra.gateway.entity.SessionEntity;
import com.unicorn.hgzero.meeting.infra.gateway.repository.SessionJpaRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 세션 Gateway 구현체
 * SessionReader, SessionWriter 인터페이스 구현
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SessionGateway implements SessionReader, SessionWriter {

    private final SessionJpaRepository sessionJpaRepository;

    @Override
    public Optional<Session> findById(String sessionId) {
        return sessionJpaRepository.findById(sessionId)
                .map(SessionEntity::toDomain);
    }

    @Override
    public List<Session> findByMeetingId(String meetingId) {
        return sessionJpaRepository.findByMeetingId(meetingId).stream()
                .map(SessionEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public Optional<Session> findActiveSesionByMeetingId(String meetingId) {
        return sessionJpaRepository.findActiveSessionByMeetingId(meetingId)
                .map(SessionEntity::toDomain);
    }

    @Override
    public List<Session> findByStartedBy(String startedBy) {
        return sessionJpaRepository.findByStartedBy(startedBy).stream()
                .map(SessionEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public Session save(Session session) {
        SessionEntity entity = SessionEntity.fromDomain(session);
        SessionEntity savedEntity = sessionJpaRepository.save(entity);
        return savedEntity.toDomain();
    }

    @Override
    public void delete(String sessionId) {
        sessionJpaRepository.deleteById(sessionId);
    }
}
