package cn.lihongjie.coal.supplier.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.supplier.dto.CreateSupplierDto;
import cn.lihongjie.coal.supplier.dto.SupplierDto;
import cn.lihongjie.coal.supplier.dto.UpdateSupplierDto;
import cn.lihongjie.coal.supplier.entity.SupplierEntity;
import cn.lihongjie.coal.supplier.mapper.SupplierMapper;
import cn.lihongjie.coal.supplier.repository.SupplierRepository;

import jakarta.annotation.PostConstruct;

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 SupplierService extends BaseService<SupplierEntity, SupplierRepository> {

    @Autowired SupplierRepository repository;

    @Autowired SupplierMapper mapper;
    @Autowired ConversionService conversionService;

    @PostConstruct
    public void init() {}

    public SupplierDto create(CreateSupplierDto request) {

        SupplierEntity entity = mapper.toEntity(request);

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

    public SupplierDto update(UpdateSupplierDto request) {
        SupplierEntity 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 SupplierDto getById(String id) {

        SupplierEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

    public Page<SupplierDto> list(CommonQuery query) {

        Page<SupplierEntity> page =
                repository.findAll(
                        query.specification(conversionService),
                        PageRequest.of(
                                query.getPageNo(),
                                query.getPageSize(),
                                Sort.by(query.getOrders())));

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