package com.ikon.projectmanagement.service.impl;

import com.ikon.projectmanagement.dto.request.RoleRequestDto;
import com.ikon.projectmanagement.dto.response.RoleResponseDto;
import com.ikon.projectmanagement.entity.Role;
import com.ikon.projectmanagement.mapper.RoleMapper;
import com.ikon.projectmanagement.repository.RoleRepository;
import com.ikon.projectmanagement.service.RoleService;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {

    private final RoleRepository roleRepository;
    private final RoleMapper roleMapper;

    @Override
    public List<RoleResponseDto> getAllRoles() {
        return roleRepository.findAll().stream()
                .map(roleMapper::toResponseDto)
                .collect(Collectors.toList());
    }

    @Override
    public RoleResponseDto getRoleById(UUID id) {
        Role role = roleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Role not found with ID: " + id));
        return roleMapper.toResponseDto(role);
    }

    @Override
    public RoleResponseDto createRole(RoleRequestDto dto) {
        Role role = roleMapper.toEntity(dto);
        Role savedRole = roleRepository.save(role);
        return roleMapper.toResponseDto(savedRole);
    }

    @Override
    public RoleResponseDto updateRole(UUID id, RoleRequestDto dto) {
        Role role = roleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Role not found with ID: " + id));
        roleMapper.updateEntity(role, dto);
        Role updatedRole = roleRepository.save(role);
        return roleMapper.toResponseDto(updatedRole);
    }

    @Override
    public void deleteRole(UUID id) {
        Role role = roleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Role not found with ID: " + id));
        roleRepository.delete(role);
    }
}
