use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
use uuid::Uuid;

use crate::dto::PermissionResp;
use crate::entity::permission;
use crate::error::AuthResult;

/// Permission read-only service — list permissions within a tenant.
///
/// Permissions are seeded by the system and not typically created via API.
pub struct PermissionService;

impl PermissionService {
    /// List all active permissions within a tenant.
    pub async fn list(
        tenant_id: Uuid,
        db: &sea_orm::DatabaseConnection,
    ) -> AuthResult<Vec<PermissionResp>> {
        let perms = permission::Entity::find()
            .filter(permission::Column::TenantId.eq(tenant_id))
            .filter(permission::Column::DeletedAt.is_null())
            .all(db)
            .await
            .map_err(|e| crate::error::AuthError::Validation(e.to_string()))?;

        Ok(perms
            .iter()
            .map(|p| PermissionResp {
                id: p.id,
                code: p.code.clone(),
                name: p.name.clone(),
                resource: p.resource.clone(),
                action: p.action.clone(),
                description: p.description.clone(),
            })
            .collect())
    }
}
