"""Entity history routes — query, restore, and undo entity snapshots."""

from __future__ import annotations

import uuid

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.db import get_db
from app.deps import get_current_user, require_permission
from app.schemas.entity_history import EntityHistoryListResponse, EntityHistoryResponse, RestoreRequest
from app.services import entity_history_service

router = APIRouter(prefix="/api/v1/entity-history", tags=["entity-history"])


def _entry_to_dict(e) -> dict:
    """Serialize an EntityHistory ORM object to dict."""
    return {
        "id": str(e.id),
        "entity_type": e.entity_type,
        "entity_id": str(e.entity_id),
        "action": e.action,
        "snapshot_before": e.snapshot_before,
        "snapshot_after": e.snapshot_after,
        "changes": e.changes,
        "user_id": str(e.user_id) if e.user_id else None,
        "created_at": e.created_at.isoformat() if e.created_at else None,
    }


@router.get("/{entity_type}/{entity_id}", response_model=EntityHistoryListResponse)
async def get_entity_history(
    entity_type: str,
    entity_id: str,
    limit: int = Query(50, ge=1, le=200),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """Get history entries for an entity, newest first."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    try:
        eid = uuid.UUID(entity_id)
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid entity_id") from None
    entries = await entity_history_service.get_entity_history(
        db, tenant_id, entity_type, eid, limit=limit
    )
    return EntityHistoryListResponse(
        items=[EntityHistoryResponse(**_entry_to_dict(e)) for e in entries],
        total=len(entries),
    )


@router.post("/restore")
async def restore_from_history(
    body: RestoreRequest,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("contacts:write")),
):
    """Restore an entity from a history entry."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    user_id = uuid.UUID(current_user["user_id"])
    try:
        hid = uuid.UUID(body.history_id)
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid history_id") from None
    try:
        return await entity_history_service.restore_from_history(db, tenant_id, hid, user_id)
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e)) from None


@router.post("/undo/{entity_type}/{entity_id}")
async def undo_last_action(
    entity_type: str,
    entity_id: str,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("contacts:write")),
):
    """Undo the most recent action for an entity."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    user_id = uuid.UUID(current_user["user_id"])
    try:
        eid = uuid.UUID(entity_id)
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid entity_id") from None
    try:
        return await entity_history_service.undo_last_action(
            db, tenant_id, user_id, entity_type, eid
        )
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e)) from None
