use ringspace::{
    common::types::*, invite::create_invite, member::enroll_member, ring::create_managed_ring,
    site::create_site,
};
use sqlx::{Connection, Sqlite, SqliteConnection, migrate, query};
pub const DATABASE_URL: &str = "sqlite://ringspace-test.db?mode=memory";

pub async fn db_setup() -> SqliteConnection {
    let mut conn = SqliteConnection::connect(DATABASE_URL).await.unwrap();
    migrate!("db/migrations").run(&mut conn).await.unwrap();
    // Create a test ring
    //
    // Create a test site
    //
    // Join 'em

    // Define a Managed Ring
    let managed_ring = ManagedRing::new(
        "Test Ring",
        "https://test.com",
        "A test ring for testing purposes",
    );

    // Define a Site
    let site = Site::new(
        "Taggart's Blog",
        "https://taggart-tech.com",
        "Taggart's blog",
    );

    create_managed_ring(
        &mut conn,
        &managed_ring.name,
        &managed_ring.url,
        &managed_ring.description,
        true,
    )
    .await
    .unwrap();

    // Create site
    create_site(&mut conn, &site.name, &site.url, &site.description, true)
        .await
        .unwrap();

    // Enroll Site in ring
    enroll_member(
        &mut conn,
        &site.name,
        &site.url,
        &site.description,
        &site.public_signing_key,
        managed_ring.id,
    )
    .await
    .unwrap();

    // Manually create the joined ring (without enrollment approval)
    query(
        "
        INSERT INTO joined_rings (name, url, description, public_signing_key)
        VALUES (?, ?, ?, ?)
        ",
    )
    .bind(managed_ring.name)
    .bind(managed_ring.url)
    .bind(managed_ring.description)
    .bind(managed_ring.public_signing_key)
    .execute(&mut conn)
    .await
    .unwrap();

    // Manually create the membership
    query(
        "
        INSERT INTO memberships (ring_id, site_id)
        VALUES (?, ?)
        ",
    )
    .bind(1)
    .bind(1)
    .execute(&mut conn)
    .await
    .unwrap();

    conn
}
