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

import com.unicorn.hgzero.meeting.biz.domain.Meeting;
import com.unicorn.hgzero.meeting.biz.usecase.out.MeetingReader;
import com.unicorn.hgzero.meeting.biz.usecase.out.MeetingWriter;
import com.unicorn.hgzero.meeting.infra.gateway.entity.MeetingEntity;
import com.unicorn.hgzero.meeting.infra.gateway.repository.MeetingJpaRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

/**
 * 회의 Gateway 구현체
 * MeetingReader, MeetingWriter 인터페이스 구현
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MeetingGateway implements MeetingReader, MeetingWriter {

    private final MeetingJpaRepository meetingJpaRepository;

    @Override
    public Optional<Meeting> findById(String meetingId) {
        return meetingJpaRepository.findById(meetingId)
                .map(MeetingEntity::toDomain);
    }

    @Override
    public List<Meeting> findByOrganizerId(String organizerId) {
        return meetingJpaRepository.findByOrganizerId(organizerId).stream()
                .map(MeetingEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<Meeting> findByStatus(String status) {
        return meetingJpaRepository.findByStatus(status).stream()
                .map(MeetingEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<Meeting> findByOrganizerIdAndStatus(String organizerId, String status) {
        return meetingJpaRepository.findByOrganizerIdAndStatus(organizerId, status).stream()
                .map(MeetingEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<Meeting> findByScheduledTimeBetween(LocalDateTime startTime, LocalDateTime endTime) {
        return meetingJpaRepository.findByScheduledAtBetween(startTime, endTime).stream()
                .map(MeetingEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<Meeting> findByTemplateId(String templateId) {
        return meetingJpaRepository.findByTemplateId(templateId).stream()
                .map(MeetingEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public Meeting save(Meeting meeting) {
        MeetingEntity entity = MeetingEntity.fromDomain(meeting);
        MeetingEntity savedEntity = meetingJpaRepository.save(entity);
        return savedEntity.toDomain();
    }

    @Override
    public void delete(String meetingId) {
        meetingJpaRepository.deleteById(meetingId);
    }
}
