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

import com.unicorn.hgzero.meeting.biz.domain.Template;
import com.unicorn.hgzero.meeting.biz.usecase.out.TemplateReader;
import com.unicorn.hgzero.meeting.biz.usecase.out.TemplateWriter;
import com.unicorn.hgzero.meeting.infra.gateway.entity.TemplateEntity;
import com.unicorn.hgzero.meeting.infra.gateway.repository.TemplateJpaRepository;
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 구현체
 * TemplateReader, TemplateWriter 인터페이스 구현
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TemplateGateway implements TemplateReader, TemplateWriter {

    private final TemplateJpaRepository templateJpaRepository;

    @Override
    public Optional<Template> findById(String templateId) {
        return templateJpaRepository.findById(templateId)
                .map(TemplateEntity::toDomain);
    }

    @Override
    public List<Template> findByCategory(String category) {
        return templateJpaRepository.findByCategory(category).stream()
                .map(TemplateEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<Template> findByIsPublic(Boolean isPublic) {
        return templateJpaRepository.findByIsPublic(isPublic).stream()
                .map(TemplateEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<Template> findByCreatedBy(String createdBy) {
        return templateJpaRepository.findByCreatedBy(createdBy).stream()
                .map(TemplateEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<Template> findByCategoryAndIsPublic(String category, Boolean isPublic) {
        return templateJpaRepository.findByCategoryAndIsPublic(category, isPublic).stream()
                .map(TemplateEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public List<Template> findByNameContaining(String name) {
        return templateJpaRepository.findByNameContaining(name).stream()
                .map(TemplateEntity::toDomain)
                .collect(Collectors.toList());
    }

    @Override
    public Template save(Template template) {
        TemplateEntity entity = TemplateEntity.fromDomain(template);
        TemplateEntity savedEntity = templateJpaRepository.save(entity);
        return savedEntity.toDomain();
    }

    @Override
    public void delete(String templateId) {
        templateJpaRepository.deleteById(templateId);
    }
}
