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

import com.unicorn.hgzero.ai.biz.domain.ProcessedTranscript;
import com.unicorn.hgzero.ai.biz.gateway.TranscriptGateway;
import com.unicorn.hgzero.ai.infra.gateway.entity.ProcessedTranscriptEntity;
import com.unicorn.hgzero.ai.infra.gateway.repository.ProcessedTranscriptJpaRepository;
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 구현체
 * JPA Repository를 사용한 회의록 영속성 관리
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TranscriptGatewayImpl implements TranscriptGateway {

    private final ProcessedTranscriptJpaRepository repository;

    @Override
    public ProcessedTranscript save(ProcessedTranscript transcript) {
        log.debug("Saving transcript: transcriptId={}, meetingId={}",
            transcript.getTranscriptId(), transcript.getMeetingId());

        ProcessedTranscriptEntity entity = ProcessedTranscriptEntity.fromDomain(transcript);
        ProcessedTranscriptEntity saved = repository.save(entity);

        log.info("Transcript saved successfully: transcriptId={}", saved.getTranscriptId());
        return saved.toDomain();
    }

    @Override
    public Optional<ProcessedTranscript> findById(String transcriptId) {
        log.debug("Finding transcript by id: {}", transcriptId);
        return repository.findById(transcriptId)
                .map(ProcessedTranscriptEntity::toDomain);
    }

    @Override
    public Optional<ProcessedTranscript> findByMeetingId(String meetingId) {
        log.debug("Finding transcript by meetingId: {}", meetingId);
        return repository.findByMeetingId(meetingId)
                .map(ProcessedTranscriptEntity::toDomain);
    }

    @Override
    public List<ProcessedTranscript> findByMeetingIds(List<String> meetingIds) {
        log.debug("Finding transcripts by meetingIds: count={}", meetingIds.size());
        return repository.findByMeetingIdIn(meetingIds).stream()
                .map(ProcessedTranscriptEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProcessedTranscript> findByStatus(String status) {
        log.debug("Finding transcripts by status: {}", status);
        return repository.findByStatus(status).stream()
                .map(ProcessedTranscriptEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public boolean existsByMeetingId(String meetingId) {
        log.debug("Checking transcript existence by meetingId: {}", meetingId);
        return repository.existsByMeetingId(meetingId);
    }

    @Override
    public void delete(String transcriptId) {
        log.debug("Deleting transcript: {}", transcriptId);
        repository.deleteById(transcriptId);
        log.info("Transcript deleted successfully: {}", transcriptId);
    }
}
