from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api import deps
from app.crud.crud_journal import journal
from app.models.journal import EntityType
from app.schemas.journal import JournalEntryResponse, EntityJournalResponse
from typing import List

router = APIRouter(tags=["journal"])


@router.get("/{entity_type}/{entity_id}", response_model=EntityJournalResponse)
async def get_entity_journal(
    entity_type: str,
    entity_id: int,
    limit: int = 100,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Get journal entries for a specific entity (PPR, LOCAL_FLIGHT, ARRIVAL, or DEPARTURE).
    
    The journal is immutable - entries are created automatically by the backend
    when changes are made. This endpoint is read-only.
    
    Parameters:
    - entity_type: One of 'PPR', 'LOCAL_FLIGHT', 'ARRIVAL', 'DEPARTURE'
    - entity_id: The ID of the entity
    - limit: Maximum number of entries to return (default 100)
    """
    # Validate entity type
    try:
        entity = EntityType[entity_type.upper()]
    except KeyError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Invalid entity_type. Must be one of: {', '.join([e.value for e in EntityType])}"
        )
    
    entries = journal.get_entity_journal(db, entity, entity_id, limit=limit)
    
    return EntityJournalResponse(
        entity_type=entity_type,
        entity_id=entity_id,
        entries=entries,
        total_entries=len(entries)
    )


@router.get("/user/{username}", response_model=List[JournalEntryResponse])
async def get_user_journal(
    username: str,
    limit: int = 100,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Get all journal entries created by a specific user.
    
    This endpoint is read-only and returns entries in reverse chronological order.
    """
    entries = journal.get_user_journal(db, username, limit=limit)
    return entries
