import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))

import pytest
from fastapi.testclient import TestClient
from app.main import app
from app.core.database import execute_query

client = TestClient(app)

@pytest.fixture(scope="function", autouse=True)
def setup_and_teardown():
    """Setup and teardown for each test."""
    # Setup: Clear the database tables before each test
    execute_query("DELETE FROM sag_tags;")
    execute_query("DELETE FROM sag_relationer;")
    execute_query("DELETE FROM sag_sager;")
    yield
    # Teardown: Clear the database tables after each test
    execute_query("DELETE FROM sag_tags;")
    execute_query("DELETE FROM sag_relationer;")
    execute_query("DELETE FROM sag_sager;")

def test_create_case():
    """Test creating a new case."""
    response = client.post("/api/v1/cases", json={
        "titel": "Test Case",
        "beskrivelse": "This is a test case.",
        "template_key": "ticket",
        "status": "åben",
        "customer_id": 1,
        "ansvarlig_bruger_id": 2,
        "created_by_user_id": 3,
        "deadline": "2026-02-01T12:00:00"
    })
    assert response.status_code == 200
    data = response.json()
    assert data["titel"] == "Test Case"
    assert data["status"] == "åben"

def test_list_cases():
    """Test listing cases."""
    # Create a case
    client.post("/api/v1/cases", json={
        "titel": "Test Case",
        "beskrivelse": "This is a test case.",
        "template_key": "ticket",
        "status": "åben",
        "customer_id": 1,
        "ansvarlig_bruger_id": 2,
        "created_by_user_id": 3,
        "deadline": "2026-02-01T12:00:00"
    })

    # List cases
    response = client.get("/api/v1/cases")
    assert response.status_code == 200
    data = response.json()
    assert len(data) == 1
    assert data[0]["titel"] == "Test Case"

def test_soft_delete_case():
    """Test soft-deleting a case."""
    # Create a case
    response = client.post("/api/v1/cases", json={
        "titel": "Test Case",
        "beskrivelse": "This is a test case.",
        "template_key": "ticket",
        "status": "åben",
        "customer_id": 1,
        "ansvarlig_bruger_id": 2,
        "created_by_user_id": 3,
        "deadline": "2026-02-01T12:00:00"
    })
    case_id = response.json()["id"]

    # Soft-delete the case
    delete_response = client.delete(f"/api/v1/cases/{case_id}")
    assert delete_response.status_code == 200

    # Verify the case is soft-deleted
    list_response = client.get("/api/v1/cases")
    assert list_response.status_code == 200
    data = list_response.json()
    assert len(data) == 0