package cn.lihongjie.coal.jobPost.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.common.Ctx;
import cn.lihongjie.coal.jobPost.dto.CreateJobPostDto;
import cn.lihongjie.coal.jobPost.dto.JobPostDto;
import cn.lihongjie.coal.jobPost.dto.UpdateJobPostDto;
import cn.lihongjie.coal.jobPost.entity.JobPostEntity;
import cn.lihongjie.coal.jobPost.mapper.JobPostMapper;
import cn.lihongjie.coal.jobPost.repository.JobPostRepository;

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 JobPostService extends BaseService<JobPostEntity, JobPostRepository> {
    @Autowired private JobPostRepository repository;

    @Autowired private JobPostMapper mapper;

    @Autowired private ConversionService conversionService;

    public JobPostDto create(CreateJobPostDto request) {
        JobPostEntity entity = mapper.toEntity(request);

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

    public JobPostDto update(UpdateJobPostDto request) {
        JobPostEntity 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 JobPostDto getById(String id) {
        JobPostEntity entity = repository.get(id);

        return mapper.toDto(entity);
    }

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

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

    public JobPostDto findByName(String name) {

        JobPostEntity post = repository.findByNameAndOrganizationId(name, Ctx.currentUser().getOrganizationId());
        
        return mapper.toDto(post);

    }
}
