package com.example.springip.lab3.service;

import com.example.springip.lab3.dao.PositionRepository;
import com.example.springip.lab3.models.Company;
import com.example.springip.lab3.models.Employee;
import com.example.springip.lab3.models.Position;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class PositionService {

    private PositionRepository positionRepository;

    public PositionService(PositionRepository positionRepository) {
        this.positionRepository = positionRepository;
    }

    @Transactional
    public Position addPosition(String name) {
        if (!StringUtils.hasText(name)) {
            throw new IllegalArgumentException("Employee's data is null or empty");
        }
        final Position position = new Position(name);
        positionRepository.save(position);
        return position;
    }

    @Transactional
    public Position findPosition(Long id) {
        final Position position = positionRepository.findById(id).orElse(null);
        if (position == null) {
            throw new EntityNotFoundException(String.format("Position with id [%s] is not found", id));
        }
        return position;
    }

    @Transactional(readOnly = true)
    public List<Position> findAllPositions() {
        return positionRepository.findAll();
    }

    @Transactional
    public Position updatePosition(Long id, String name) {
        if (!StringUtils.hasText(name)) {
            throw new IllegalArgumentException("Employee's data is null or empty");
        }
        final Position currentPosition = findPosition(id);
        currentPosition.setName(name);

        return positionRepository.save(currentPosition);
    }

    @Transactional
    public Position deletePosition(Long id) {
        final Position p = findPosition(id);
        positionRepository.delete(p);
        return p;
    }

    @Transactional
    public void deleteAllPositions() {
        positionRepository.deleteAll();
    }


}
