package com.saas.admin.repository;

import com.saas.admin.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * Repository for Role entity
 */
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
    
    /**
     * Find role by name
     */
    Optional<Role> findByName(String name);
    
    /**
     * Find all active roles
     */
    List<Role> findByIsActiveTrue();
    
    /**
     * Find all system roles
     */
    List<Role> findByIsSystemTrue();
    
    /**
     * Find non-system roles (can be deleted)
     */
    List<Role> findByIsSystemFalse();
    
    /**
     * Check if role exists by name
     */
    boolean existsByName(String name);
    
    /**
     * Find role with its permissions eagerly loaded
     */
    @Query("SELECT r FROM Role r LEFT JOIN FETCH r.rolePermissions rp LEFT JOIN FETCH rp.permission WHERE r.id = :roleId")
    Optional<Role> findByIdWithPermissions(@Param("roleId") Long roleId);
    
    /**
     * Find role by name with permissions eagerly loaded
     */
    @Query("SELECT r FROM Role r LEFT JOIN FETCH r.rolePermissions rp LEFT JOIN FETCH rp.permission WHERE r.name = :name")
    Optional<Role> findByNameWithPermissions(@Param("name") String name);
}
