from fastapi import APIRouter, Depends, Query
from typing import Optional
from auth.models import TokenPayload
from auth.dependencies import require_permission
from equipment.models import (
    NoteCreate, NoteUpdate, NoteInDB, NoteListResponse,
)
from equipment import service

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


@router.get("", response_model=NoteListResponse)
async def list_notes(
    search: Optional[str] = Query(None),
    category: Optional[str] = Query(None),
    device_id: Optional[str] = Query(None),
    user_id: Optional[str] = Query(None),
    _user: TokenPayload = Depends(require_permission("equipment", "view")),
):
    notes = service.list_notes(
        search=search, category=category,
        device_id=device_id, user_id=user_id,
    )
    return NoteListResponse(notes=notes, total=len(notes))


@router.get("/{note_id}", response_model=NoteInDB)
async def get_note(
    note_id: str,
    _user: TokenPayload = Depends(require_permission("equipment", "view")),
):
    return service.get_note(note_id)


@router.post("", response_model=NoteInDB, status_code=201)
async def create_note(
    body: NoteCreate,
    _user: TokenPayload = Depends(require_permission("equipment", "add")),
):
    return service.create_note(body, created_by=_user.name or _user.email)


@router.put("/{note_id}", response_model=NoteInDB)
async def update_note(
    note_id: str,
    body: NoteUpdate,
    _user: TokenPayload = Depends(require_permission("equipment", "edit")),
):
    return service.update_note(note_id, body)


@router.patch("/{note_id}/status", response_model=NoteInDB)
async def toggle_note_status(
    note_id: str,
    body: NoteUpdate,
    _user: TokenPayload = Depends(require_permission("equipment", "edit")),
):
    return service.update_note(note_id, body)


@router.delete("/{note_id}", status_code=204)
async def delete_note(
    note_id: str,
    _user: TokenPayload = Depends(require_permission("equipment", "delete")),
):
    service.delete_note(note_id)
