//! OIDC providers — read-only listing of what's currently in
//! `oidc_providers`. Editing providers is operator-side via the
//! `--oidc-config` TOML or hand-inserted SQL; the dashboard surfaces them
//! so admins can confirm what's wired up without leaving the UI.

use super::shared::{html_escape, require_admin};
use crate::api::error::ApiError;
use crate::api::middleware::AuthedUser;
use crate::api::state::AppState;
use axum::extract::Extension;
use axum::response::Html;
use std::fmt::Write as _;
use std::sync::Arc;

pub async fn index(
    Extension(state): Extension<Arc<AppState>>,
    admin: AuthedUser,
) -> Result<Html<String>, ApiError> {
    require_admin(&admin)?;
    let providers = state
        .db
        .oidc_provider_list_enabled()
        .await
        .map_err(|e| ApiError::Internal(e.to_string()))?;
    let mut s = String::new();
    s.push_str(
        r##"<div class="space-y-4">
  <header>
    <h2 class="text-lg font-semibold">OIDC providers</h2>
    <p class="text-xs text-slate-500 mt-1">Read-only. Add/edit via <code>--oidc-config</code> TOML at startup, or by inserting into the <code>oidc_providers</code> table.</p>
  </header>"##,
    );
    if providers.is_empty() {
        s.push_str(
            r##"<p class="text-slate-500 text-sm">No OIDC providers configured.</p></div>"##,
        );
        return Ok(Html(s));
    }
    s.push_str(
        r##"<div class="rounded-md border border-slate-800 bg-slate-900 overflow-hidden">
  <table class="w-full text-sm">
    <thead class="text-xs uppercase text-slate-500 bg-slate-950"><tr>
      <th class="text-left font-medium px-3 py-2">Name</th>
      <th class="text-left font-medium px-3 py-2">Display name</th>
      <th class="text-left font-medium px-3 py-2">Issuer</th>
      <th class="text-left font-medium px-3 py-2">Client ID</th>
      <th class="text-left font-medium px-3 py-2">Scopes</th>
      <th class="text-left font-medium px-3 py-2">Redirect</th>
    </tr></thead>
    <tbody class="divide-y divide-slate-800">"##,
    );
    for p in &providers {
        let _ = write!(
            s,
            r##"<tr>
  <td class="px-3 py-2 font-medium text-slate-200">{name}</td>
  <td class="px-3 py-2 text-slate-300">{display}</td>
  <td class="px-3 py-2 text-slate-400 font-mono text-xs">{issuer}</td>
  <td class="px-3 py-2 text-slate-400 font-mono text-xs">{client_id}</td>
  <td class="px-3 py-2 text-slate-400 text-xs">{scopes}</td>
  <td class="px-3 py-2 text-slate-400 font-mono text-xs">{redirect}</td>
</tr>"##,
            name = html_escape(&p.name),
            display = html_escape(p.display_name.as_deref().unwrap_or("")),
            issuer = html_escape(&p.issuer_url),
            client_id = html_escape(&p.client_id),
            scopes = html_escape(&p.scopes),
            redirect = html_escape(&p.redirect_url),
        );
    }
    s.push_str("</tbody></table></div></div>");
    Ok(Html(s))
}
