from goodnews.db import connect, init_db


def test_deleting_a_brief_cascades_to_items(tmp_path):
    """The orphaned-items bug: a brief was deleted while its items survived,
    because FK enforcement is per-connection in SQLite. connect() turns it on,
    so ON DELETE CASCADE must now clear the items and leave no FK violations.
    """
    c = connect(str(tmp_path / "t.db")); init_db(c)
    assert c.execute("PRAGMA foreign_keys").fetchone()[0] == 1  # enforced

    c.execute("INSERT INTO sources (id, name, feed_url) VALUES (1, 'S', 'http://s/f')")
    c.execute(
        "INSERT INTO articles (id, source_id, canonical_url, title, url_hash, published_at) "
        "VALUES (1, 1, 'http://s/a', 'A', 'h1', '2026-01-01T00:00:00')"
    )
    c.execute("INSERT INTO daily_briefs (id, brief_date, title) VALUES (9, '2026-01-01', 'B')")
    c.execute("INSERT INTO daily_brief_items (brief_id, article_id, rank) VALUES (9, 1, 1)")
    c.commit()

    c.execute("DELETE FROM daily_briefs WHERE id = 9")
    c.commit()

    assert c.execute("SELECT COUNT(*) FROM daily_brief_items").fetchone()[0] == 0
    assert c.execute("PRAGMA foreign_key_check").fetchall() == []
