package com.saas.admin.repository;

import com.saas.admin.entity.Permission;
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 Permission entity
 */
@Repository
public interface PermissionRepository extends JpaRepository<Permission, Long> {
    
    /**
     * Find permission by resource and action
     * Example: resource="tenant", action="read" → "tenant:read"
     */
    Optional<Permission> findByResourceAndAction(String resource, String action);
    
    /**
     * Find all permissions for a specific resource
     * Example: resource="tenant" → ["tenant:read", "tenant:write", "tenant:delete"]
     */
    List<Permission> findByResource(String resource);
    
    /**
     * Find all active permissions
     */
    List<Permission> findByIsActiveTrue();
    
    /**
     * Find all system permissions
     */
    List<Permission> findByIsSystemTrue();
    
    /**
     * Find non-system permissions (can be deleted)
     */
    List<Permission> findByIsSystemFalse();
    
    /**
     * Check if permission exists by resource and action
     */
    boolean existsByResourceAndAction(String resource, String action);
    
    /**
     * Get all distinct resources
     * Example: ["tenant", "user", "voip", "cost", "call"]
     */
    @Query("SELECT DISTINCT p.resource FROM Permission p ORDER BY p.resource")
    List<String> findAllResources();
    
    /**
     * Get all distinct actions
     * Example: ["read", "write", "delete", "manage"]
     */
    @Query("SELECT DISTINCT p.action FROM Permission p ORDER BY p.action")
    List<String> findAllActions();
    
    /**
     * Find permissions by IDs
     */
    @Query("SELECT p FROM Permission p WHERE p.id IN :permissionIds")
    List<Permission> findByIdIn(@Param("permissionIds") List<Long> permissionIds);
}
