"""Pytest — TestClient, erillinen test.db, uniikki data per testi."""

from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from main import app, get_db
from models import Base

test_engine = create_engine(
    "sqlite:///./test.db", connect_args={"check_same_thread": False}
)
TestSession = sessionmaker(autocommit=False, autoflush=False, bind=test_engine)
Base.metadata.create_all(bind=test_engine)


def override_get_db():
    db = TestSession()
    try:
        yield db
    finally:
        db.close()


app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)


def _create_author(name="Eino Leino", email=None):
    """Apufunktio kirjoittajan luomiseen testeissä."""
    if email is None:
        email = f"{name.lower().replace(' ', '.')}@example.com"
    return client.post(
        "/authors/", json={"name": name, "email": email}
    ).json()


# --- Author-testit ---


def test_create_author():
    response = client.post(
        "/authors/",
        json={"name": "Aleksis Kivi", "email": "aleksis@example.com", "bio": "Suomen kansalliskirjailija"},
    )
    assert response.status_code == 201
    assert response.json()["name"] == "Aleksis Kivi"
    assert response.json()["bio"] == "Suomen kansalliskirjailija"
    assert "id" in response.json()


def test_list_authors():
    _create_author("Minna Canth", "minna.canth@example.com")
    response = client.get("/authors/")
    assert response.status_code == 200
    assert len(response.json()) >= 1


def test_get_author_by_id():
    created = _create_author("Väinö Linna", "vaino.linna@example.com")
    response = client.get(f"/authors/{created['id']}")
    assert response.status_code == 200
    assert response.json()["id"] == created["id"]


def test_get_author_not_found():
    response = client.get("/authors/99999")
    assert response.status_code == 404


def test_update_author():
    created = _create_author("Vanha Nimi", "vanha.nimi@example.com")
    response = client.put(
        f"/authors/{created['id']}",
        json={"name": "Uusi Nimi", "email": "uusi.nimi@example.com"},
    )
    assert response.status_code == 200
    assert response.json()["name"] == "Uusi Nimi"


def test_delete_author():
    created = _create_author("Poistettava Kirjailija", "poistettava@example.com")
    response = client.delete(f"/authors/{created['id']}")
    assert response.status_code == 204
    response = client.get(f"/authors/{created['id']}")
    assert response.status_code == 404


# --- Post-testit ---


def test_create_post():
    author = _create_author("Tove Jansson", "tove.jansson@example.com")
    response = client.post(
        "/posts/",
        json={"title": "Muumipeikko ja pyrstötähti", "content": "Eräänä aamuna...", "author_id": author["id"]},
    )
    assert response.status_code == 201
    assert response.json()["title"] == "Muumipeikko ja pyrstötähti"
    assert response.json()["author_id"] == author["id"]
    assert response.json()["status"] == "draft"


def test_list_posts():
    author = _create_author("Juhani Aho", "juhani.aho@example.com")
    client.post(
        "/posts/",
        json={"title": "Rautatie", "content": "Junasta kertova novelli.", "author_id": author["id"]},
    )
    response = client.get("/posts/")
    assert response.status_code == 200
    assert len(response.json()) >= 1


def test_get_post_by_id():
    author = _create_author("Elias Lönnrot", "elias.lonnrot@example.com")
    created = client.post(
        "/posts/",
        json={"title": "Kalevala", "content": "Vaka vanha Väinämöinen.", "author_id": author["id"]},
    ).json()
    response = client.get(f"/posts/{created['id']}")
    assert response.status_code == 200
    assert response.json()["id"] == created["id"]


def test_get_post_not_found():
    response = client.get("/posts/99999")
    assert response.status_code == 404


def test_update_post():
    author = _create_author("Joel Lehtonen", "joel.lehtonen@example.com")
    created = client.post(
        "/posts/",
        json={"title": "Vanha otsikko", "content": "Alkuperäinen teksti.", "author_id": author["id"]},
    ).json()
    response = client.put(
        f"/posts/{created['id']}",
        json={"title": "Päivitetty otsikko", "content": "Muokattu teksti.", "author_id": author["id"], "status": "published"},
    )
    assert response.status_code == 200
    assert response.json()["title"] == "Päivitetty otsikko"
    assert response.json()["status"] == "published"


def test_delete_post():
    author = _create_author("Aino Kallas", "aino.kallas@example.com")
    created = client.post(
        "/posts/",
        json={"title": "Poistettava postaus", "content": "Tämä poistetaan.", "author_id": author["id"]},
    ).json()
    response = client.delete(f"/posts/{created['id']}")
    assert response.status_code == 204
    response = client.get(f"/posts/{created['id']}")
    assert response.status_code == 404


def test_post_belongs_to_author():
    author = _create_author("Sofi Oksanen", "sofi.oksanen@example.com")
    post = client.post(
        "/posts/",
        json={"title": "Puhdistus", "content": "Romaani Virosta.", "author_id": author["id"]},
    ).json()
    assert post["author_id"] == author["id"]
