package com.ikon.projectmanagement.service.impl;

import com.ikon.projectmanagement.dto.request.EmployeeRequestDto;
import com.ikon.projectmanagement.dto.response.EmployeeResponseDto;
import com.ikon.projectmanagement.entity.Employee;
import com.ikon.projectmanagement.mapper.EmployeeMapper;
import com.ikon.projectmanagement.repository.EmployeeRepository;
import com.ikon.projectmanagement.service.EmployeeService;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class EmployeeServiceImpl implements EmployeeService {

    private final EmployeeRepository employeeRepository;
    private final EmployeeMapper employeeMapper;

    @Override
    public List<EmployeeResponseDto> getAllEmployees() {
        return employeeRepository.findAll().stream()
                .map(employeeMapper::toResponseDto)
                .collect(Collectors.toList());
    }

    @Override
    public EmployeeResponseDto getEmployeeById(String id) {
        Employee employee = employeeRepository.findByEmpId(id)
                .orElseThrow(() -> new RuntimeException("Employee not found with ID: " + id));
        return employeeMapper.toResponseDto(employee);
    }

    @Override
    public EmployeeResponseDto createEmployee(EmployeeRequestDto dto) {
        // Check if employee already exists
        if (dto.getEmpId() != null && employeeRepository.findByEmpId(dto.getEmpId()).isPresent()) {
            throw new RuntimeException("Employee already exists with ID: " + dto.getEmpId());
        }
        Employee employee = employeeMapper.toEntity(dto);
        Employee savedEmployee = employeeRepository.save(employee);
        return employeeMapper.toResponseDto(savedEmployee);
    }

    @Override
    public EmployeeResponseDto updateEmployee(String id, EmployeeRequestDto dto) {
        Employee employee = employeeRepository.findByEmpId(id)
                .orElseThrow(() -> new RuntimeException("Employee not found with ID: " + id));
        employeeMapper.updateEntity(employee, dto);
        Employee updatedEmployee = employeeRepository.save(employee);
        return employeeMapper.toResponseDto(updatedEmployee);
    }

    @Override
    public void deleteEmployee(String id) {
        Employee employee = employeeRepository.findByEmpId(id)
                .orElseThrow(() -> new RuntimeException("Employee not found with ID: " + id));
        employeeRepository.delete(employee);
    }
}
