package ru.somecompany.service;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import ru.somecompany.domain.CompanyEntity;
import ru.somecompany.domain.CreateCompanyRequest;
import ru.somecompany.repository.CompanyRepository;

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

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

@Service
@RequiredArgsConstructor
public class CompanyServiceImpl implements CompanyService {

    private final CompanyRepository companyRepository;

    @Override
    public List<CompanyEntity> getCompanies() {
        return companyRepository.findAll();
    }

    @Override
    public CompanyEntity createCompany(CreateCompanyRequest companyRequest) {
        var entity = CompanyEntity.builder()
                .name(companyRequest.getName())
                .address(companyRequest.getAddress())
                .build();
        return companyRepository.save(entity);
    }

    @Override
    public CompanyEntity updateCompany(UUID companyId, CreateCompanyRequest companyRequest) {
        var company = getById(companyId);
        company.setName(companyRequest.getName());
        company.setAddress(companyRequest.getAddress());
        return companyRepository.save(company);
    }

    @Override
    public void deleteCompany(UUID companyId) {
        var company = getById(companyId);
        companyRepository.delete(company);
    }

    @Override
    public CompanyEntity getCompany(UUID companyId) {
        return getById(companyId);
    }

    private CompanyEntity getById(UUID companyId) {
        return companyRepository.findById(companyId)
                .orElseThrow(() -> notFound("Компания не найдена"));
    }
}
