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

import com.unicorn.hgzero.meeting.biz.domain.MinutesSection;
import com.unicorn.hgzero.meeting.biz.usecase.out.MinutesSectionReader;
import com.unicorn.hgzero.meeting.biz.usecase.out.MinutesSectionWriter;
import com.unicorn.hgzero.meeting.infra.gateway.entity.MinutesSectionEntity;
import com.unicorn.hgzero.meeting.infra.gateway.repository.MinutesSectionJpaRepository;
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 구현체
 * MinutesSectionReader, MinutesSectionWriter 인터페이스 구현
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MinutesSectionGateway implements MinutesSectionReader, MinutesSectionWriter {

    private final MinutesSectionJpaRepository sectionJpaRepository;

    @Override
    public Optional<MinutesSection> findById(String sectionId) {
        return sectionJpaRepository.findById(sectionId)
                .map(MinutesSectionEntity::toDomain);
    }

    @Override
    public List<MinutesSection> findByMinutesIdOrderByOrder(String minutesId) {
        return sectionJpaRepository.findByMinutesIdOrderByOrderAsc(minutesId).stream()
                .map(MinutesSectionEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<MinutesSection> findByMinutesIdAndType(String minutesId, String type) {
        return sectionJpaRepository.findByMinutesIdAndType(minutesId, type).stream()
                .map(MinutesSectionEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<MinutesSection> findByMinutesIdAndVerified(String minutesId, Boolean verified) {
        return sectionJpaRepository.findByMinutesIdAndVerified(minutesId, verified).stream()
                .map(MinutesSectionEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<MinutesSection> findByMinutesIdAndLocked(String minutesId, Boolean locked) {
        return sectionJpaRepository.findByMinutesIdAndLocked(minutesId, locked).stream()
                .map(MinutesSectionEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<MinutesSection> findByLockedBy(String lockedBy) {
        return sectionJpaRepository.findByLockedBy(lockedBy).stream()
                .map(MinutesSectionEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public MinutesSection save(MinutesSection section) {
        MinutesSectionEntity entity = MinutesSectionEntity.fromDomain(section);
        MinutesSectionEntity savedEntity = sectionJpaRepository.save(entity);
        return savedEntity.toDomain();
    }

    @Override
    public void delete(String sectionId) {
        sectionJpaRepository.deleteById(sectionId);
    }
}
