use std::{collections::BTreeMap, path::Path, sync::Arc};

use configinator::{IntegrationConfig, IntegrationProtocol};
use gobetween::Integration;
use notatype::Kind;
use stewball::{
    Storage,
    saferlmdb::{self, EnvBuilder},
};

#[test]
fn integration() -> Result<(), Box<dyn std::error::Error>> {
    let store_dir = Path::new(".ordinary").join("store");

    if std::fs::read_dir(&store_dir).is_ok() {
        std::fs::remove_dir_all(&store_dir)?;
    }

    std::fs::create_dir_all(&store_dir)?;

    let env = Arc::new(unsafe {
        let mut env_builder = EnvBuilder::new()?;
        env_builder.set_maxreaders(126)?;
        env_builder.set_mapsize(16384 * 2560)?;
        env_builder.set_maxdbs(13)?;
        env_builder.open(
            store_dir.to_str().expect("store dir is not str"),
            saferlmdb::open::Flags::empty(),
            0o600,
        )?
    });

    let storage = Storage::new(
        vec![],
        vec![],
        [0u8; 32],
        env,
        store_dir.join("search"),
        false,
    )?;

    let integration = Integration::new(
        IntegrationConfig {
            idx: 0,
            name: "test".into(),
            protocol: IntegrationProtocol::Http {
                method: "GET".into(),
                headers: vec![],
                send_encoding: configinator::IntegrationProtocolHttpEncoding::Json,
                recv_encoding: configinator::IntegrationProtocolHttpEncoding::Json,
            },
            endpoint: "https://jsonplaceholder.typicode.com/todos/1".into(),
            send: Kind::List {
                kind: Box::new(Kind::String),
            },
            recv: Kind::Object {
                name: "test".into(),
                fields: vec![],
            },
            secrets: None,
        },
        Arc::new(storage),
        &BTreeMap::new(),
    )?;

    let mut send_builder = flexbuffers::Builder::new(flexbuffers::BuilderOptions::SHARE_NONE);
    let mut send_builder_vec = send_builder.start_vector();

    send_builder_vec.push("one");
    send_builder_vec.push("two");
    send_builder_vec.push("three");

    send_builder_vec.end_vector();

    integration.invoke(send_builder.view())?;

    Ok(())
}
