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

import com.unicorn.hgzero.meeting.biz.domain.MeetingAnalysis;
import com.unicorn.hgzero.meeting.biz.usecase.out.MeetingAnalysisReader;
import com.unicorn.hgzero.meeting.biz.usecase.out.MeetingAnalysisWriter;
import com.unicorn.hgzero.meeting.infra.gateway.entity.MeetingAnalysisEntity;
import com.unicorn.hgzero.meeting.infra.gateway.repository.MeetingAnalysisJpaRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 회의 분석 Gateway
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MeetingAnalysisGateway implements MeetingAnalysisReader, MeetingAnalysisWriter {

    private final MeetingAnalysisJpaRepository repository;

    @Override
    public Optional<MeetingAnalysis> findByMeetingId(String meetingId) {
        log.debug("Finding meeting analysis by meetingId: {}", meetingId);
        return repository.findByMeetingId(meetingId)
                .map(MeetingAnalysisEntity::toDomain);
    }

    @Override
    public Optional<MeetingAnalysis> findById(String analysisId) {
        log.debug("Finding meeting analysis by analysisId: {}", analysisId);
        return repository.findById(analysisId)
                .map(MeetingAnalysisEntity::toDomain);
    }

    @Override
    public Optional<MeetingAnalysis> findByMinutesId(String minutesId) {
        log.debug("Finding meeting analysis by minutesId: {}", minutesId);
        return repository.findByMinutesId(minutesId)
                .map(MeetingAnalysisEntity::toDomain);
    }

    @Override
    public Optional<MeetingAnalysis> findLatestByMeetingId(String meetingId) {
        log.debug("Finding latest meeting analysis by meetingId: {}", meetingId);
        return repository.findFirstByMeetingIdOrderByCreatedAtDesc(meetingId)
                .map(MeetingAnalysisEntity::toDomain);
    }

    @Override
    public MeetingAnalysis save(MeetingAnalysis analysis) {
        log.debug("Saving meeting analysis: {}", analysis.getAnalysisId());
        MeetingAnalysisEntity entity = MeetingAnalysisEntity.fromDomain(analysis);
        MeetingAnalysisEntity savedEntity = repository.save(entity);
        return savedEntity.toDomain();
    }

    @Override
    public void delete(String analysisId) {
        log.debug("Deleting meeting analysis: {}", analysisId);
        repository.deleteById(analysisId);
    }
}