package cn.lihongjie.coal.smsTemplate.service;

import cn.lihongjie.coal.base.dto.CommonQuery;
import cn.lihongjie.coal.base.dto.IdRequest;
import cn.lihongjie.coal.base.service.BaseService;
import cn.lihongjie.coal.smsTemplate.dto.CreateSmsTemplateDto;
import cn.lihongjie.coal.smsTemplate.dto.SmsTemplateDto;
import cn.lihongjie.coal.smsTemplate.dto.UpdateSmsTemplateDto;
import cn.lihongjie.coal.smsTemplate.entity.SmsTemplateEntity;
import cn.lihongjie.coal.smsTemplate.mapper.SmsTemplateMapper;
import cn.lihongjie.coal.smsTemplate.repository.SmsTemplateRepository;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional
public class SmsTemplateService extends BaseService<SmsTemplateEntity, SmsTemplateRepository> {
    @Autowired private SmsTemplateRepository repository;

    @Autowired private SmsTemplateMapper mapper;

    @Autowired private ConversionService conversionService;

    public SmsTemplateDto create(CreateSmsTemplateDto request) {
        SmsTemplateEntity entity = mapper.toEntity(request);

        this.repository.save(entity);
        return getById(entity.getId());
    }

    public SmsTemplateDto update(UpdateSmsTemplateDto request) {
        SmsTemplateEntity entity = this.repository.get(request.getId());
        this.mapper.updateEntity(entity, request);

        this.repository.save(entity);

        return getById(entity.getId());
    }

    public void delete(IdRequest request) {
        this.repository.deleteAllById(request.getIds());
    }

    public SmsTemplateDto getById(String id) {
        SmsTemplateEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

    public Page<SmsTemplateDto> list(CommonQuery query) {
        Page<SmsTemplateEntity> page =
                repository.findAll(
                        query.specification(conversionService),
                        PageRequest.of(
                                query.getPageNo(),
                                query.getPageSize(),
                                Sort.by(query.getOrders())));

        return page.map(this.mapper::toDto);
    }
}
