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

from .. import models, schemas
from ..database import get_db
from ..services.report_service import report_summary

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


@router.get("/results", response_model=list[schemas.AnalysisResultOut])
def list_results(db: Session = Depends(get_db)):
    return db.query(models.AnalysisResult).order_by(models.AnalysisResult.created_at.desc()).all()


@router.get("/results/{result_id}", response_model=schemas.AnalysisResultOut)
def get_result(result_id: int, db: Session = Depends(get_db)):
    result = db.get(models.AnalysisResult, result_id)
    if result is None:
        raise HTTPException(status_code=404, detail="Tahlil natijasi topilmadi")
    return result


@router.delete("/results/{result_id}", status_code=204)
def delete_result(result_id: int, db: Session = Depends(get_db)):
    result = db.get(models.AnalysisResult, result_id)
    if result is None:
        raise HTTPException(status_code=404, detail="Tahlil natijasi topilmadi")
    db.delete(result)
    db.commit()
    return Response(status_code=204)


@router.get("/results/{result_id}/summary")
def get_result_summary(result_id: int, db: Session = Depends(get_db)):
    result = db.get(models.AnalysisResult, result_id)
    if result is None:
        raise HTTPException(status_code=404, detail="Tahlil natijasi topilmadi")
    return report_summary(result)
