from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Response, status
from sqlalchemy.orm import Session

from backend.app.api.deps import get_db
from backend.app.db import crud, schemas

router = APIRouter(prefix="/products", tags=["products"])


@router.get("", response_model=list[schemas.ProductWithSnapshot])
def list_products(skip: int = 0, limit: int = 50, db: Session = Depends(get_db)) -> list[schemas.ProductWithSnapshot]:
    # on retourne la liste paginée de produits enrichis avec les derniers snapshots
    return crud.list_products_with_snapshots(db, skip=skip, limit=limit)


@router.post("", response_model=schemas.ProductWithSnapshot, status_code=status.HTTP_201_CREATED)
def create_product(
    payload: schemas.ProductCreateWithSnapshot,
    db: Session = Depends(get_db),
) -> schemas.ProductWithSnapshot:
    """
    Crée un produit avec ses données de snapshot initiales.
    Les données proviennent de la prévisualisation (/scrape/preview).
    """
    product = crud.create_product_with_snapshot(db, payload)
    # Retourner le produit enrichi avec le snapshot créé
    return crud.get_product_with_snapshot(db, product.id)


@router.get("/{product_id}", response_model=schemas.ProductWithSnapshot)
def read_product(product_id: int, db: Session = Depends(get_db)) -> schemas.ProductWithSnapshot:
    product = crud.get_product_with_snapshot(db, product_id)
    if not product:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Produit introuvable")
    return product


@router.put("/{product_id}", response_model=schemas.ProductRead)
def update_product(product_id: int, payload: schemas.ProductUpdate, db: Session = Depends(get_db)) -> schemas.ProductRead:
    product = crud.get_product(db, product_id)
    if not product:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Produit introuvable")
    # mise à jour partielle des champs éditables
    return crud.update_product(db, product, payload)


@router.delete("/{product_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_product(product_id: int, db: Session = Depends(get_db)) -> Response:
    product = crud.get_product(db, product_id)
    if not product:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Produit introuvable")
    # suppression définitive en base
    crud.remove_product(db, product)
    return Response(status_code=status.HTTP_204_NO_CONTENT)


@router.get("/{product_id}/snapshots", response_model=list[schemas.ProductSnapshotRead])
def list_snapshots(
    product_id: int,
    days: int | None = None,
    limit: int = 1000,
    db: Session = Depends(get_db),
) -> list[schemas.ProductSnapshotRead]:
    """Retourne les snapshots d'un produit, filtrés par nombre de jours."""
    product = crud.get_product(db, product_id)
    if not product:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Produit introuvable")
    return crud.list_snapshots(db, product_id, days=days, limit=limit)
