package com.example.springip.lab3.service;

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 {
    @PersistenceContext
    private EntityManager em;

    @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);
        em.persist(position);
        return position;
    }

    @Transactional
    public Position findPosition(Long id) {
        final Position position = em.find(Position.class, id);
        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 em.createQuery("select p from Position p", Position.class)
                .getResultList();
    }

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

        return em.merge(currentPosition);
    }

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

    @Transactional
    public void deleteAllPositions() {
        em.createQuery("delete from Position").executeUpdate();
    }


}
