package br.gov.sigefp.admin.service;

import br.gov.sigefp.admin.api.dto.RoleDTO;
import br.gov.sigefp.admin.domain.Role;
import br.gov.sigefp.admin.repository.RoleRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * Serviço de aplicação para gestão de perfis/roles.
 */
@Service
@RequiredArgsConstructor
@Transactional
public class RoleService {

    private final RoleRepository roleRepository;

    public RoleDTO create(RoleDTO dto) {
        if (roleRepository.existsByCode(dto.getCode())) {
            throw new IllegalArgumentException("Código de perfil já existe: " + dto.getCode());
        }

        Role role = Role.builder()
                .code(dto.getCode())
                .name(dto.getName())
                .description(dto.getDescription())
                .build();

        Role saved = roleRepository.save(role);
        return toDTO(saved);
    }

    public RoleDTO update(UUID id, RoleDTO dto) {
        Role role = roleRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Perfil não encontrado: " + id));

        if (dto.getCode() != null && !dto.getCode().equals(role.getCode())) {
            if (roleRepository.existsByCode(dto.getCode())) {
                throw new IllegalArgumentException("Código de perfil já existe: " + dto.getCode());
            }
            role.setCode(dto.getCode());
        }

        if (dto.getName() != null) {
            role.setName(dto.getName());
        }
        if (dto.getDescription() != null) {
            role.setDescription(dto.getDescription());
        }

        Role saved = roleRepository.save(role);
        return toDTO(saved);
    }

    @Transactional(readOnly = true)
    public RoleDTO findById(UUID id) {
        Role role = roleRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Perfil não encontrado: " + id));
        return toDTO(role);
    }

    @Transactional(readOnly = true)
    public Page<RoleDTO> findAll(Pageable pageable) {
        return roleRepository.findAll(pageable).map(this::toDTO);
    }

    private RoleDTO toDTO(Role role) {
        return RoleDTO.builder()
                .id(role.getId())
                .code(role.getCode())
                .name(role.getName())
                .description(role.getDescription())
                .build();
    }
}

