use askama::Template;
use axum::{
    extract::{Path, State},
    response::{Html, IntoResponse as _, Response},
};
use interim_models::{expression::PgExpressionAny, portal::Portal, workspace::Workspace};
use interim_pgtypes::pg_attribute::PgAttribute;
use serde::Deserialize;
use sqlx::postgres::types::Oid;
use uuid::Uuid;

use crate::{
    app::AppDbConn,
    errors::AppError,
    navigator::Navigator,
    settings::Settings,
    user::CurrentUser,
    workspace_nav::{NavLocation, RelLocation, WorkspaceNav},
    workspace_pooler::{RoleAssignment, WorkspacePooler},
};

#[derive(Clone, Debug, Deserialize)]
pub(super) struct PathParams {
    portal_id: Uuid,
    rel_oid: u32,
    workspace_id: Uuid,
}

/// HTTP GET handler for the table viewer page of a [`Portal`]. This handler
/// performs some relatively simple queries pertaining to table structure, but
/// the bulk of the query logic resides in the [`super::get_data_handler`]
/// module.
pub(super) async fn get(
    State(settings): State<Settings>,
    State(mut workspace_pooler): State<WorkspacePooler>,
    AppDbConn(mut app_db): AppDbConn,
    CurrentUser(current_user): CurrentUser,
    navigator: Navigator,
    Path(PathParams {
        portal_id,
        workspace_id,
        rel_oid,
    }): Path<PathParams>,
) -> Result<Response, AppError> {
    // FIXME auth

    let workspace = Workspace::with_id(workspace_id)
        .fetch_one(&mut app_db)
        .await?;
    let portal = Portal::with_id(portal_id).fetch_one(&mut app_db).await?;

    let mut workspace_client = workspace_pooler
        .acquire_for(portal.workspace_id, RoleAssignment::User(current_user.id))
        .await?;

    let attrs = PgAttribute::all_for_rel(portal.class_oid)
        .fetch_all(&mut workspace_client)
        .await?;
    let attr_names: Vec<String> = attrs.iter().map(|attr| attr.attname.clone()).collect();

    #[derive(Template)]
    #[template(path = "portal_table.html")]
    struct ResponseTemplate {
        attr_names: Vec<String>,
        filter: Option<PgExpressionAny>,
        settings: Settings,
        navbar: WorkspaceNav,
    }
    Ok(Html(
        ResponseTemplate {
            attr_names,
            filter: portal.table_filter.0,
            navbar: WorkspaceNav::builder()
                .navigator(navigator)
                .workspace(workspace.clone())
                .populate_rels(&mut app_db, &mut workspace_client)
                .await?
                .current(NavLocation::Rel(
                    Oid(rel_oid),
                    Some(RelLocation::Portal(portal.id)),
                ))
                .build()?,
            settings,
        }
        .render()?,
    )
    .into_response())
}
