"""Intel items endpoints — list and manage threat intelligence items."""

import uuid
from typing import Optional

from fastapi import APIRouter, Depends, Query
from pydantic import BaseModel
from sqlalchemy.orm import Session

from app.database import get_db
from app.dependencies.auth import get_current_user
from app.models.intel import IntelItem
from app.models.user import User

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


class IntelItemOut(BaseModel):
    id: uuid.UUID
    technique_id: Optional[uuid.UUID] = None
    url: str
    title: Optional[str] = None
    source: Optional[str] = None
    detected_at: Optional[str] = None
    reviewed: bool

    class Config:
        from_attributes = True


@router.get("/items", response_model=list[IntelItemOut])
def list_intel_items(
    technique_id: Optional[uuid.UUID] = Query(None, description="Filter by technique"),
    limit: int = Query(50, ge=1, le=200),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    """List threat intelligence items, optionally filtered by technique."""
    query = db.query(IntelItem).order_by(IntelItem.detected_at.desc())
    if technique_id:
        query = query.filter(IntelItem.technique_id == technique_id)
    items = query.limit(limit).all()
    return [
        IntelItemOut(
            id=item.id,
            technique_id=item.technique_id,
            url=item.url,
            title=item.title,
            source=item.source,
            detected_at=item.detected_at.isoformat() if item.detected_at else None,
            reviewed=item.reviewed,
        )
        for item in items
    ]
