/*
 * Copyright (C) 2022  Aravinth Manivannan <realaravinth@batsense.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
use actix_web::{web, HttpResponse, Responder};
use actix_web_httpauth::middleware::HttpAuthentication;
use serde::{Deserialize, Serialize};

use libconductor::EventType;

use crate::errors::*;
use crate::AppCtx;
use crate::*;

use super::bearerauth;

pub mod routes {
    use super::*;
    #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
    pub struct Webhook {
        pub post_event: &'static str,
    }
    impl Webhook {
        pub const fn new() -> Self {
            Self {
                post_event: "/api/v1/events/new",
            }
        }
    }
}

pub fn services(cfg: &mut web::ServiceConfig) {
    cfg.service(post_event);
}

#[actix_web_codegen_const_routes::post(
    path = "API_V1_ROUTES.webhook.post_event",
    wrap = "HttpAuthentication::bearer(bearerauth)"
)]
async fn post_event(ctx: AppCtx, payload: web::Json<EventType>) -> ServiceResult<impl Responder> {
    ctx.conductor.process(payload.into_inner()).await;
    Ok(HttpResponse::Created())
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use actix_web::{http::StatusCode, test, App};

    #[actix_rt::test]
    async fn submit_works() {
        let settings = Settings::new().unwrap();
        let ctx = AppCtx::new(crate::ctx::Ctx::new(&settings).await);
        let app = test::init_service(
            App::new()
                .app_data(ctx.clone())
                .configure(crate::routes::services),
        )
        .await;

        let creds = settings.creds.clone();
        let auth = format!("Bearer {}", creds.token,);

        let msg = EventType::NewSite {
            hostname: "demo.librepages.org".into(),
            branch: "librepages".into(),
            path: "/tmp/librepages".into(),
        };

        // upload json
        let upload_json = test::call_service(
            &app,
            test::TestRequest::post()
                .append_header((actix_web::http::header::AUTHORIZATION, auth.clone()))
                .uri(API_V1_ROUTES.webhook.post_event)
                .set_json(&msg)
                .to_request(),
        )
        .await;
        assert_eq!(upload_json.status(), StatusCode::CREATED);
    }
}
