use super::*;
use crate::core::db::create_connection;
use tempfile::tempdir;

fn setup_test_db() -> Connection {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let conn = create_connection(&db_path).unwrap();

    conn.execute_batch(
        "CREATE TABLE raw_payloads (
            id INTEGER PRIMARY KEY,
            source TEXT NOT NULL,
            project_id INTEGER,
            resource_type TEXT NOT NULL,
            gitlab_id TEXT NOT NULL,
            fetched_at INTEGER NOT NULL,
            content_encoding TEXT NOT NULL DEFAULT 'identity',
            payload_hash TEXT NOT NULL,
            payload BLOB NOT NULL
        );
        CREATE UNIQUE INDEX uq_raw_payloads_dedupe
            ON raw_payloads(project_id, resource_type, gitlab_id, payload_hash);",
    )
    .unwrap();

    conn
}

#[test]
fn test_store_and_read_payload() {
    let conn = setup_test_db();
    let payload = serde_json::json!({"title": "Test Issue", "id": 123});
    let json_bytes = serde_json::to_vec(&payload).unwrap();

    let id = store_payload(
        &conn,
        StorePayloadOptions {
            project_id: Some(1),
            resource_type: "issue",
            gitlab_id: "123",
            json_bytes: &json_bytes,
            compress: false,
        },
    )
    .unwrap();

    let result = read_payload(&conn, id).unwrap().unwrap();
    assert_eq!(result["title"], "Test Issue");
}

#[test]
fn test_compression_roundtrip() {
    let conn = setup_test_db();
    let payload = serde_json::json!({"data": "x".repeat(1000)});
    let json_bytes = serde_json::to_vec(&payload).unwrap();

    let id = store_payload(
        &conn,
        StorePayloadOptions {
            project_id: Some(1),
            resource_type: "issue",
            gitlab_id: "456",
            json_bytes: &json_bytes,
            compress: true,
        },
    )
    .unwrap();

    let result = read_payload(&conn, id).unwrap().unwrap();
    assert_eq!(result["data"], "x".repeat(1000));
}

#[test]
fn test_deduplication() {
    let conn = setup_test_db();
    let payload = serde_json::json!({"id": 789});
    let json_bytes = serde_json::to_vec(&payload).unwrap();

    let id1 = store_payload(
        &conn,
        StorePayloadOptions {
            project_id: Some(1),
            resource_type: "issue",
            gitlab_id: "789",
            json_bytes: &json_bytes,
            compress: false,
        },
    )
    .unwrap();

    let id2 = store_payload(
        &conn,
        StorePayloadOptions {
            project_id: Some(1),
            resource_type: "issue",
            gitlab_id: "789",
            json_bytes: &json_bytes,
            compress: false,
        },
    )
    .unwrap();

    assert_eq!(id1, id2);
}
