package org.fuseri.modulecertificate.certificate;


import jakarta.servlet.http.HttpServletResponse;
import org.fuseri.model.dto.certificate.CertificateCreateDto;
import org.fuseri.model.dto.certificate.CertificateGenerateDto;
import org.fuseri.model.dto.certificate.CertificateSimpleDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.Instant;
import java.util.List;

@Service
@Transactional
public class CertificateFacade {

    private final CertificateService certificateService;
    private final CertificateMapper certificateMapper;

    @Autowired
    public CertificateFacade(CertificateService certificateService, CertificateMapper certificateMapper) {
        this.certificateService = certificateService;
        this.certificateMapper = certificateMapper;
    }


    @Transactional(readOnly = true)
    public CertificateSimpleDto findById(Long id) {
        return certificateMapper.mapToSimpleDto(certificateService.findById(id));
    }

    @Transactional()
    public CertificateGenerateDto generate(CertificateCreateDto certificateCreateDto, HttpServletResponse response) throws IOException {

        var certificate = certificateMapper.mapToCertificate(certificateCreateDto,
                Instant.now(), certificateService.generateCertificateFileName(certificateCreateDto));
        var saved = certificateService.save(certificate);
        certificateService.generateCertificateFile(certificateCreateDto, certificate.getCertificateFileName(), response);
        return certificateMapper.mapToCertificateGenerateDto(saved);
    }


    @Transactional(readOnly = true)
    public List<CertificateSimpleDto> findByUserId(Long userId) {
        return certificateMapper.mapToList(certificateService.findByUserId(userId));
    }


    @Transactional(readOnly = true)
    public List<CertificateSimpleDto> findByUserIdAndCourseId(Long userId, Long courseId) {
        return certificateMapper.mapToList(certificateService.findByUserIdAndCourseId(userId, courseId));
    }

    @Transactional(readOnly = true)
    public Page<CertificateSimpleDto> findAll(Pageable pageable) {
        return certificateMapper.mapToPageDto(certificateService.findAll(pageable));
    }

    @Transactional(readOnly = true)
    public void deleteCertificate(Long certificateId) {
        certificateService.delete(certificateId);
    }
}
