# app/modules/prospecting/routes/api/admin_interactions.py
"""
Admin API routes for interaction logging and follow-ups.
"""

import logging
from datetime import date

from fastapi import APIRouter, Depends, Path, Query
from sqlalchemy.orm import Session

from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.modules.prospecting.schemas.interaction import (
    InteractionCreate,
    InteractionListResponse,
    InteractionResponse,
)
from app.modules.prospecting.services.interaction_service import interaction_service
from app.modules.tenancy.schemas.auth import UserContext

router = APIRouter()
logger = logging.getLogger(__name__)


@router.get("/prospects/{prospect_id}/interactions", response_model=InteractionListResponse)
def get_prospect_interactions(
    prospect_id: int = Path(...),
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get all interactions for a prospect."""
    interactions = interaction_service.get_for_prospect(db, prospect_id)
    return InteractionListResponse(
        items=[InteractionResponse.model_validate(i) for i in interactions],
        total=len(interactions),
    )


@router.post("/prospects/{prospect_id}/interactions", response_model=InteractionResponse)
def create_interaction(
    data: InteractionCreate,
    prospect_id: int = Path(...),
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Log a new interaction for a prospect."""
    interaction = interaction_service.create(
        db,
        prospect_id=prospect_id,
        user_id=current_admin.id,
        data=data.model_dump(exclude_none=True),
    )
    db.commit()
    return InteractionResponse.model_validate(interaction)


@router.get("/interactions/upcoming")
def get_upcoming_actions(
    before: date | None = Query(None),
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get interactions with upcoming follow-up actions."""
    interactions = interaction_service.get_upcoming_actions(db, before_date=before)
    return [InteractionResponse.model_validate(i) for i in interactions]
