use axum::{Router, extract::Form, http::StatusCode, routing::post};
use color_eyre::eyre::{self, Context};
use dotenvy_macro::dotenv;
use error::WithStatusCode;
use serde::Deserialize;
use serenity::all::{ExecuteWebhook, Http, Webhook};
use tracing::instrument;
use tracing_error::ErrorLayer;
use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};

mod error;

const SPECULATION_WEBHOOK: &'static str = dotenv!("SPECULATION_WEBHOOK");
const IDEA_WEBHOOK: &'static str = dotenv!("IDEA_WEBHOOK");
const LISTEN_ADDR: &'static str = dotenv!("LISTEN_ADDR");

#[tokio::main]
async fn main() -> eyre::Result<()> {
    color_eyre::install()?;

    tracing_subscriber::registry()
        .with(ErrorLayer::default())
        .with(
            EnvFilter::try_from_default_env()
                .or_else(|_| EnvFilter::try_new("info"))
                .unwrap(),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();

    let app = Router::new()
        .route("/api/speculate", post(speculate))
        .route("/api/page-idea", post(page_idea));

    let listener = tokio::net::TcpListener::bind(LISTEN_ADDR)
        .await
        .wrap_err("Failed to listen on that port")?;
    axum::serve(listener, app)
        .await
        .wrap_err("Failed to run axum service")?;
    Ok(())
}

#[derive(Deserialize, Debug)]
struct Speculation {
    speculation: String,
}

#[instrument]
async fn speculate(Form(speculation): Form<Speculation>) -> Result<maud::Markup, error::Error> {
    let discord_http = Http::new("");

    let webhook = Webhook::from_url(&discord_http, SPECULATION_WEBHOOK)
        .await
        .wrap_err("Failed to initialize webhook")
        .with_status_code(StatusCode::INTERNAL_SERVER_ERROR)?;

    let builder = ExecuteWebhook::new()
        .content(speculation.speculation)
        .username("Anonymous speculator");
    webhook
        .execute(&discord_http, false, builder)
        .await
        .wrap_err("Could not execute webhook")
        .with_status_code(StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(maud::html! {
        p { "Speculation launched at high speed directly into our DMs" }
    })
}

#[derive(Deserialize, Debug)]
struct PageIdea {
    #[serde(rename = "page-idea")]
    page_idea: String,
}

#[instrument]
async fn page_idea(Form(page_idea): Form<PageIdea>) -> Result<maud::Markup, error::Error> {
    let discord_http = Http::new("");

    let webhook = Webhook::from_url(&discord_http, IDEA_WEBHOOK)
        .await
        .wrap_err("Failed to initialize webhook")
        .with_status_code(StatusCode::INTERNAL_SERVER_ERROR)?;

    let builder = ExecuteWebhook::new()
        .content(page_idea.page_idea)
        .username("Anonymous ideator");
    webhook
        .execute(&discord_http, false, builder)
        .await
        .wrap_err("Could not execute webhook")
        .with_status_code(StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(maud::html! {
        p { "Page idea launched at high speed directly into our DMs" }
    })
}
