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

import com.unicorn.hgzero.meeting.biz.domain.Minutes;
import com.unicorn.hgzero.meeting.biz.usecase.out.MinutesReader;
import com.unicorn.hgzero.meeting.biz.usecase.out.MinutesWriter;
import com.unicorn.hgzero.meeting.infra.gateway.entity.MinutesEntity;
import com.unicorn.hgzero.meeting.infra.gateway.repository.MinutesJpaRepository;
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 구현체
 * MinutesReader, MinutesWriter 인터페이스 구현
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MinutesGateway implements MinutesReader, MinutesWriter {

    private final MinutesJpaRepository minutesJpaRepository;

    @Override
    public Optional<Minutes> findById(String minutesId) {
        return minutesJpaRepository.findById(minutesId)
                .map(MinutesEntity::toDomain);
    }

    @Override
    public List<Minutes> findByMeetingId(String meetingId) {
        return minutesJpaRepository.findByMeetingId(meetingId).stream()
                .map(MinutesEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public Optional<Minutes> findLatestByMeetingId(String meetingId) {
        return minutesJpaRepository.findFirstByMeetingIdOrderByVersionDesc(meetingId)
                .map(MinutesEntity::toDomain);
    }

    @Override
    public List<Minutes> findByCreatedBy(String createdBy) {
        return minutesJpaRepository.findByCreatedBy(createdBy).stream()
                .map(MinutesEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<Minutes> findByStatus(String status) {
        return minutesJpaRepository.findByStatus(status).stream()
                .map(MinutesEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<Minutes> findByFinalizedBy(String finalizedBy) {
        return minutesJpaRepository.findByFinalizedBy(finalizedBy).stream()
                .map(MinutesEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public Minutes save(Minutes minutes) {
        MinutesEntity entity = MinutesEntity.fromDomain(minutes);
        MinutesEntity savedEntity = minutesJpaRepository.save(entity);
        return savedEntity.toDomain();
    }

    @Override
    public void delete(String minutesId) {
        minutesJpaRepository.deleteById(minutesId);
    }
}
