from datetime import datetime
from app.db import database
from app.v1.models.platform.customer_accounts import CustomerAccount
from pymongo.errors import DuplicateKeyError
from app.v1.libraries.object import str_to_objectid
from bson import ObjectId
from fastapi import HTTPException

COLLECTION_NAME = "customer_accounts"

def create_customer_account_service(data: CustomerAccount, db: database.MongoDB) -> dict:
    collection = db[COLLECTION_NAME]
    record = data.dict()
    record["created_date"] = datetime.utcnow()
    record["updated_date"] = datetime.utcnow()

    result = collection.insert_one(record)
    new_id = str(result.inserted_id)
    record["_id"] = new_id

    # 🔄 Update related customer if customer_id exists
    if record.get("customer_id"):
        customers_collection = db["customers"]
        customers_collection.update_one(
            {"_id": str_to_objectid(record["customer_id"])},
            {"$set": {"customer_accounts_id": new_id}}
        )

    return record

def get_customer_accounts_service(account_id: str, db: database.MongoDB) -> list:
    collection = db[COLLECTION_NAME]
    query = {"account_id": account_id}
    results = list(collection.find(query))
    for doc in results:
        doc["_id"] = str(doc["_id"])
    return results

def get_customer_account_service(customer_account_id: str, db: database.MongoDB) -> dict:
    collection = db[COLLECTION_NAME]
    record = collection.find_one({"_id": str_to_objectid(customer_account_id)})
    if not record:
        return None
    record["_id"] = str(record["_id"])
    return record

def update_customer_account_service(customer_account_id: str, update_data: dict, db: database.MongoDB) -> dict:
    collection = db[COLLECTION_NAME]
    update_data["updated_date"] = datetime.utcnow()

    result = collection.update_one(
        {"_id": str_to_objectid(customer_account_id)},
        {"$set": update_data}
    )
    if result.matched_count == 0:
        raise HTTPException(status_code=404, detail="Customer account not found")

    return get_customer_account_service(customer_account_id, db)

def delete_customer_account_service(customer_account_id: str, db: database.MongoDB) -> dict:
    collection = db[COLLECTION_NAME]
    result = collection.delete_one({"_id": str_to_objectid(customer_account_id)})

    if result.deleted_count == 0:
        raise HTTPException(status_code=404, detail="Customer account not found")
    
    return {"message": "Customer account deleted successfully"}