use crate::AppState;
use axum::{http::StatusCode, response::IntoResponse, routing::get, Json, Router};
use contracts::auth_middleware::{AuthUser, require_admin};
use serde::Serialize;

pub fn router() -> Router<AppState> {
    Router::new().route("/", get(list_permissions))
}

#[derive(Serialize)]
struct PermissionEntry {
    key: String,
    module: String,
    action: String,
}

const MODULES: &[&str] = &[
    "Department Management",
    "Designation Management",
    "Internal Role Management",
    "Employee Management",
    "External Role Management",
    "External Onboarding Management",
    "Internal Dashboard Management",
    "External Dashboard Management",
    "Verification Management",
    "Approval Management",
    "Users Management",
    "Company Management",
    "Candidate Management",
    "Customer Management",
    "Photographer Management",
    "Makeup Artist Management",
    "Tutor Management",
    "Developer Management",
    "Fitness Trainer Management",
    "Graphic Designer Management",
    "Social Media Management",
    "Video Editor Management",
    "Catering Services Management",
    "UGC Content Creator Management",
    "Jobs Management",
    "Leads Management",
    "Applications Management",
    "Responses Management",
    "Review Management",
    "Pricing Management",
    "Credit Management",
    "Coupon Management",
    "Discount Management",
    "Tax Management",
    "Order Management",
    "Invoice Management",
    "Payment Gateway Management",
    "Ledger Management",
    "Knowledge Base Management",
    "Support Management",
    "Report Management",
    "SMTP Management",
    "Email Management",
    "Notifications",
    "Dashboard",
];

const ACTIONS: &[&str] = &["View", "Create", "Update", "Delete"];

async fn list_permissions(
    auth: AuthUser,
    _: axum::extract::State<AppState>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    require_admin(&auth).map_err(|_| (StatusCode::FORBIDDEN, "Admin access required".to_string()))?;
    let permissions: Vec<PermissionEntry> = MODULES
        .iter()
        .flat_map(|module| {
            ACTIONS.iter().map(|action| {
                let key = format!("{}:{}", module.replace(' ', "_").to_lowercase(), action.to_lowercase());
                PermissionEntry {
                    key,
                    module: module.to_string(),
                    action: action.to_string(),
                }
            })
        })
        .collect();

    Ok(Json(permissions))
}
