from app.v1.models.platform.templates import TemplateCreate
from datetime import datetime
from bson import ObjectId
from typing import Optional
from pymongo.collection import Collection

COLLECTION_NAME = "templates"

def create_template_service(template: TemplateCreate, db) -> dict:
    data = template.dict()
    data["created_date"] = datetime.utcnow()
    result = db[COLLECTION_NAME].insert_one(data)
    data["template_id"] = str(result.inserted_id)
    return data

def list_template_service(account_id: str, db) -> dict:
    query = {"account_id": account_id}
    cursor = db[COLLECTION_NAME].find(query)
    templates = []
    for doc in cursor:
        doc["template_id"] = str(doc["_id"])
        templates.append(doc)
    return {"total_count": len(templates), "templates": templates}

def get_template_by_id(template_id: str, db) -> Optional[dict]:
    doc = db[COLLECTION_NAME].find_one({"_id": ObjectId(template_id)})
    if doc:
        doc["template_id"] = str(doc["_id"])
        return doc
    return None
