from datetime import datetime
from pymongo.collection import Collection
from app.db import database
from ...models.saas.supportmodel import SupportActivityCreate, SupportActivityUpdate
from ...libraries.object import str_to_objectid
from typing import Optional, List
import logging

logger = logging.getLogger(__name__)

# Use a single collection for all support activities (same as internal).
COLLECTION_NAME = "support_activities"

# Allowed types for customer-facing activities.
ALLOWED_CUSTOMER_TYPES = {"ticket", "support_request", "subscription_request"}

async def create_customer_activity_service(activity: SupportActivityCreate, db: database.MongoDB) -> dict:
    """
    Insert a new customer support activity into the support_activities collection.
    Only allowed activity types are accepted.
    """
    if activity.type not in ALLOWED_CUSTOMER_TYPES:
        raise ValueError("This activity type is not permitted for customer support.")
    try:
        activities_collection: Collection = db[COLLECTION_NAME]
        activity_data = activity.dict()
        activity_data["created_date"] = datetime.utcnow()
        result = activities_collection.insert_one(activity_data)
        activity_data["_id"] = str(result.inserted_id)
        activity_data["activity_id"] = activity_data["_id"]
        logger.info("Created customer activity %s", activity_data["activity_id"])
        return activity_data
    except Exception as e:
        logger.error("Error creating customer activity: %s", e)
        raise

async def list_customer_activities_service(account_id: str, type_filter: Optional[str], skip: int, limit: int, db: database.MongoDB) -> List[dict]:
    """
    Retrieve a paginated list of customer support activities for the given account.
    Only returns records with allowed types.
    """
    try:
        activities_collection: Collection = db[COLLECTION_NAME]
        query = {"account_id": account_id, "type": {"$in": list(ALLOWED_CUSTOMER_TYPES)}}
        if type_filter:
            if type_filter not in ALLOWED_CUSTOMER_TYPES:
                raise ValueError("Invalid activity type filter for customer support")
            query["type"] = type_filter
        cursor = activities_collection.find(query).skip(skip).limit(limit).sort("created_date", -1)
        activities = []
        async for doc in cursor:
            doc["_id"] = str(doc["_id"])
            doc["activity_id"] = doc["_id"]
            activities.append(doc)
        return activities
    except Exception as e:
        logger.error("Error listing customer activities: %s", e)
        raise

async def get_customer_activity_service(activity_id: str, db: database.MongoDB) -> Optional[dict]:
    """
    Retrieve a single customer support activity by its ID.
    """
    try:
        activities_collection: Collection = db[COLLECTION_NAME]
        activity = activities_collection.find_one({"_id": str_to_objectid(activity_id)})
        if activity:
            if activity.get("type") not in ALLOWED_CUSTOMER_TYPES:
                raise ValueError("Access denied to internal activity")
            activity["_id"] = str(activity["_id"])
            activity["activity_id"] = activity["_id"]
        return activity
    except Exception as e:
        logger.error("Error retrieving customer activity %s: %s", activity_id, e)
        raise

async def update_customer_activity_service(activity_id: str, activity_update: SupportActivityUpdate, db: database.MongoDB) -> Optional[dict]:
    """
    Update an existing customer support activity.
    """
    try:
        activities_collection: Collection = db[COLLECTION_NAME]
        update_data = activity_update.dict(exclude_unset=True)
        result = activities_collection.update_one({"_id": str_to_objectid(activity_id)}, {"$set": update_data})
        if result.matched_count == 0:
            return None
        activity = activities_collection.find_one({"_id": str_to_objectid(activity_id)})
        if activity:
            if activity.get("type") not in ALLOWED_CUSTOMER_TYPES:
                raise ValueError("Access denied to internal activity")
            activity["_id"] = str(activity["_id"])
            activity["activity_id"] = activity["_id"]
        return activity
    except Exception as e:
        logger.error("Error updating customer activity %s: %s", activity_id, e)
        raise

async def delete_customer_activity_service(activity_id: str, db: database.MongoDB) -> Optional[dict]:
    """
    Delete a customer support activity and return the deleted record.
    """
    try:
        activities_collection: Collection = db[COLLECTION_NAME]
        activity = activities_collection.find_one({"_id": str_to_objectid(activity_id)})
        if not activity:
            return None
        if activity.get("type") not in ALLOWED_CUSTOMER_TYPES:
            raise ValueError("Access denied to internal activity")
        activities_collection.delete_one({"_id": str_to_objectid(activity_id)})
        activity["_id"] = str(activity["_id"])
        activity["activity_id"] = activity["_id"]
        return activity
    except Exception as e:
        logger.error("Error deleting customer activity %s: %s", activity_id, e)
        raise
