from fastapi import APIRouter, Depends, HTTPException, Query, Path, Body
from typing import Optional, List, Dict, Any
from datetime import datetime
from pydantic import BaseModel, Field
from app.db import database
from ...dependencies.auth import get_current_userdetails
from ...models.saas.supportmodel import SupportActivity, SupportActivityCreate, SupportActivityUpdate
from ...services.saas.supportcustomer import (
    create_customer_activity_service,
    list_customer_activities_service,
    get_customer_activity_service,
    update_customer_activity_service,
    delete_customer_activity_service
)

router = APIRouter()

# Allowed activity types for customer communication.
ALLOWED_CUSTOMER_TYPES = {"ticket", "support_request", "subscription_request"}

@router.post("/", response_model=SupportActivity)
async def create_customer_activity(
    activity: SupportActivityCreate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Create a new customer support activity (e.g. a ticket or support request).
    Only allowed activity types (ticket, support_request, subscription_request) can be created.
    The current user's account_id is used if not provided.
    """
    # Enforce allowed types
    if activity.type not in ALLOWED_CUSTOMER_TYPES:
        raise HTTPException(status_code=400, detail="Activity type not allowed for customer support")
    if not activity.account_id:
        activity = activity.copy(update={"account_id": current_user.get("account_id")})
    # Optionally force user_id to the current user's id
    activity = activity.copy(update={"user_id": current_user.get("_id")})
    try:
        new_activity = await create_customer_activity_service(activity, db)
        return new_activity
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to create customer activity: {str(e)}")

@router.get("/", response_model=List[SupportActivity])
async def list_customer_activities(
    account_id: str = Query(..., description="Account ID to filter customer support activities"),
    activity_type: Optional[str] = Query(None, description="Optional filter by allowed activity type"),
    skip: int = Query(0, ge=0),
    limit: int = Query(10, ge=1),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Retrieve a paginated list of customer support activities for an account.
    Only returns records with allowed types.
    """
    try:
        activities = await list_customer_activities_service(account_id, activity_type, skip, limit, db)
        return activities
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to list customer activities: {str(e)}")

@router.get("/{activity_id}", response_model=SupportActivity)
async def get_customer_activity(
    activity_id: str = Path(..., description="Customer support activity ID"),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Retrieve details for a single customer support activity.
    """
    try:
        activity = await get_customer_activity_service(activity_id, db)
        if not activity:
            raise HTTPException(status_code=404, detail="Activity not found")
        # Optionally, check that the activity's account_id matches current user's account
        if activity.get("account_id") != current_user.get("account_id"):
            raise HTTPException(status_code=403, detail="Not authorized to view this activity")
        return activity
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to retrieve activity: {str(e)}")

@router.put("/{activity_id}", response_model=SupportActivity)
async def update_customer_activity(
    activity_id: str,
    activity_update: SupportActivityUpdate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Update an existing customer support activity.
    Only activities created by the customer (i.e. with allowed types) can be updated.
    """
    try:
        updated = await update_customer_activity_service(activity_id, activity_update, db)
        if not updated:
            raise HTTPException(status_code=404, detail="Activity not found")
        # Ensure the activity belongs to the customer's account
        if updated.get("account_id") != current_user.get("account_id"):
            raise HTTPException(status_code=403, detail="Not authorized to update this activity")
        return updated
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to update activity: {str(e)}")

@router.delete("/{activity_id}", response_model=SupportActivity)
async def delete_customer_activity(
    activity_id: str = Path(..., description="Customer support activity ID"),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Delete a customer support activity.
    """
    try:
        deleted = await delete_customer_activity_service(activity_id, db)
        if not deleted:
            raise HTTPException(status_code=404, detail="Activity not found")
        # Ensure the deleted record belongs to the current account
        if deleted.get("account_id") != current_user.get("account_id"):
            raise HTTPException(status_code=403, detail="Not authorized to delete this activity")
        return deleted
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to delete activity: {str(e)}")
