package com.saas.admin.repository;

import com.saas.admin.entity.Permission;
import com.saas.admin.entity.Role;
import com.saas.admin.entity.RolePermission;
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 RolePermission junction table
 */
@Repository
public interface RolePermissionRepository extends JpaRepository<RolePermission, Long> {
    
    /**
     * Find all permissions for a role
     */
    List<RolePermission> findByRole(Role role);
    
    /**
     * Find all roles that have a specific permission
     */
    List<RolePermission> findByPermission(Permission permission);
    
    /**
     * Find specific role-permission mapping
     */
    Optional<RolePermission> findByRoleAndPermission(Role role, Permission permission);
    
    /**
     * Check if role has specific permission
     */
    boolean existsByRoleAndPermission(Role role, Permission permission);
    
    /**
     * Delete all permissions for a role
     */
    void deleteByRole(Role role);
    
    /**
     * Delete all roles that have a specific permission
     */
    void deleteByPermission(Permission permission);
    
    /**
     * Get all permission strings for a role
     * Returns format ["tenant:read", "tenant:write", ...]
     */
    @Query("SELECT CONCAT(p.resource, ':', p.action) FROM RolePermission rp JOIN rp.permission p WHERE rp.role = :role AND p.isActive = true")
    List<String> findPermissionStringsByRole(@Param("role") Role role);
    
    /**
     * Get all permission strings for a role by role ID
     */
    @Query("SELECT CONCAT(p.resource, ':', p.action) FROM RolePermission rp JOIN rp.permission p WHERE rp.role.id = :roleId AND p.isActive = true")
    List<String> findPermissionStringsByRoleId(@Param("roleId") Long roleId);
}
