package ru.somecompany.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import ru.somecompany.domain.CreateVacancyRequest;
import ru.somecompany.domain.VacancyEntity;
import ru.somecompany.domain.VacancyResponse;
import ru.somecompany.mapper.VacancyMapper;
import ru.somecompany.repository.VacancyRepository;
import ru.somecompany.service.adapter.CompanyAdapter;

import java.util.List;
import java.util.UUID;

import static ru.somecompany.exception.ResourceNotFoundException.notFound;

@Slf4j
@Service
@RequiredArgsConstructor
public class VacancyServiceImpl implements VacancyService {

    private final VacancyRepository vacancyRepository;
    private final CompanyAdapter companyAdapter;
    private final VacancyMapper mapper;

    @Override
    public List<VacancyEntity> getVacancies() {
        return vacancyRepository.findAll();
    }

    @Override
    public VacancyEntity createVacancy(CreateVacancyRequest request) {
        var entity = mapper.map(request);
        return vacancyRepository.save(entity);
    }

    @Override
    public VacancyEntity updateVacancy(UUID vacancyId, CreateVacancyRequest request) {
        var entity = getById(vacancyId);
        entity = mapper.map(entity, request);

        return vacancyRepository.save(entity);
    }

    @Override
    public void deleteVacancy(UUID vacancyId) {
        var entity = getById(vacancyId);
        vacancyRepository.delete(entity);
    }

    @Override
    public VacancyResponse getVacancy(UUID vacancyId) {
        var entity = getById(vacancyId);
        var company = companyAdapter.getCompanyById(entity.getCompanyId());

        return mapper.map(entity, company);
    }

    private VacancyEntity getById(UUID vacancyId) {
        var entity = vacancyRepository.findById(vacancyId);
        if (entity.isEmpty()) {
            log.warn("The vacancy with id '{}' was not found", vacancyId);
            throw notFound("Вакансия не найдена");
        }
        return entity.get();
    }
}
