use axum::{
    debug_handler,
    extract::{Path, State},
    response::Response,
};
use phono_models::{
    accessors::{Accessor, Actor, portal::PortalAccessor},
    portal::{Portal, RE_PORTAL_NAME},
};
use serde::Deserialize;
use sqlx::postgres::types::Oid;
use uuid::Uuid;
use validator::Validate;

use crate::{
    app::AppDbConn,
    errors::AppError,
    extractors::ValidatedForm,
    navigator::{Navigator, NavigatorPage as _},
    user::CurrentUser,
    workspace_pooler::WorkspacePooler,
};

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

#[derive(Debug, Deserialize, Validate)]
pub(super) struct FormBody {
    #[validate(regex(path = *RE_PORTAL_NAME))]
    name: String,
}

/// HTTP POST handler for updating a portal's name.
#[debug_handler(state = crate::app::App)]
pub(super) async fn post(
    AppDbConn(mut app_db): AppDbConn,
    State(mut pooler): State<WorkspacePooler>,
    CurrentUser(user): CurrentUser,
    navigator: Navigator,
    Path(PathParams {
        portal_id,
        rel_oid,
        workspace_id,
    }): Path<PathParams>,
    ValidatedForm(FormBody { name }): ValidatedForm<FormBody>,
) -> Result<Response, AppError> {
    let mut workspace_client = pooler
        .acquire_for(
            workspace_id,
            crate::workspace_pooler::RoleAssignment::User(user.id),
        )
        .await?;

    let portal = PortalAccessor::new()
        .id(portal_id)
        .as_actor(Actor::User(user.id))
        .verify_workspace_id(workspace_id)
        .verify_rel_oid(Oid(rel_oid))
        .verify_rel_ownership()
        .using_app_db(&mut app_db)
        .using_workspace_client(&mut workspace_client)
        .fetch_one()
        .await?;

    Portal::update()
        .id(portal.id)
        .name(name)
        .build()?
        .execute(&mut app_db)
        .await?;

    Ok(navigator
        .portal_page()
        .workspace_id(workspace_id)
        .rel_oid(Oid(rel_oid))
        .portal_id(portal.id)
        .suffix("settings/")
        .build()?
        .redirect_to())
}
