"""
Tests pour les modeles SQLAlchemy.
"""

from datetime import datetime, timezone

import pytest
from sqlalchemy import create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, sessionmaker

from pricewatch.app.db.models import (
    Base,
    PriceHistory,
    Product,
    ProductImage,
    ProductSpec,
    ScrapingLog,
)


@pytest.fixture
def session() -> Session:
    """Session SQLite in-memory pour tests de modeles."""
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
    SessionLocal = sessionmaker(bind=engine)
    session = SessionLocal()
    try:
        yield session
    finally:
        session.close()
        engine.dispose()


def test_product_relationships(session: Session):
    """Les relations principales fonctionnent (prix, images, specs, logs)."""
    product = Product(source="amazon", reference="B08N5WRWNW", url="https://example.com")

    price = PriceHistory(
        price=199.99,
        shipping_cost=0,
        stock_status="in_stock",
        fetch_method="http",
        fetch_status="success",
        fetched_at=datetime.now(timezone.utc),
    )
    image = ProductImage(image_url="https://example.com/image.jpg", position=0)
    spec = ProductSpec(spec_key="Couleur", spec_value="Noir")
    log = ScrapingLog(
        url="https://example.com",
        source="amazon",
        reference="B08N5WRWNW",
        fetch_method="http",
        fetch_status="success",
        fetched_at=datetime.now(timezone.utc),
        duration_ms=1200,
        html_size_bytes=2048,
        errors={"items": []},
        notes={"items": ["OK"]},
    )

    product.price_history.append(price)
    product.images.append(image)
    product.specs.append(spec)
    product.logs.append(log)

    session.add(product)
    session.commit()

    loaded = session.query(Product).first()
    assert loaded is not None
    assert len(loaded.price_history) == 1
    assert len(loaded.images) == 1
    assert len(loaded.specs) == 1
    assert len(loaded.logs) == 1


def test_unique_product_constraint(session: Session):
    """La contrainte unique source+reference est respectee."""
    product_a = Product(source="amazon", reference="B08N5WRWNW", url="https://example.com/a")
    product_b = Product(source="amazon", reference="B08N5WRWNW", url="https://example.com/b")

    session.add(product_a)
    session.commit()

    session.add(product_b)
    with pytest.raises(IntegrityError):
        session.commit()
    session.rollback()
