import os
import base64
import uuid
from MongoDBConnection import DB_NAME, client
from datetime import datetime, timezone

db = client[DB_NAME]
collection = db["banners"]

# Khai báo thư mục lưu ảnh (giống với Ticket và Upload)
UPLOAD_DIR = os.path.join("uploads", "upload_img")
os.makedirs(UPLOAD_DIR, exist_ok=True)

class BannerModel:
    @classmethod
    def update_banner(cls, banner_id: str, title: str, subtitle: str, badge: str, cta_text: str, image_url: str):
        updated_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
        
        clean_image_name = ""

        if image_url:
            # 1. Nếu là chuỗi Base64 (Từ Admin gửi lên)
            if image_url.startswith("data:image"):
                try:
                    # Tách lấy phần đuôi file và dữ liệu mã hóa
                    header, encoded = image_url.split(",", 1)
                    ext = header.split(";")[0].split("/")[1]
                    if ext == "jpeg": ext = "jpg"
                    
                    # Tạo tên file độc nhất
                    unique_filename = f"banner_{uuid.uuid4().hex[:8]}.{ext}"
                    filepath = os.path.join(UPLOAD_DIR, unique_filename)
                    
                    # Giải mã và lưu thành file ảnh thật vào ổ cứng
                    with open(filepath, "wb") as f:
                        f.write(base64.b64decode(encoded))
                        
                    clean_image_name = unique_filename
                except Exception as e:
                    print(f"Lỗi giải mã Base64: {e}")
                    clean_image_name = ""
            # 2. Nếu là link bình thường (Chỉ đổi tên text)
            else:
                clean_image_name = os.path.basename(str(image_url).split("?")[0].strip())

        final_file_name = os.path.basename(clean_image_name) if clean_image_name else ""

        update_data = {
            "title": title,
            "subtitle": subtitle,
            "badge": badge,
            "ctaText": cta_text,
            "imageUrl": final_file_name,
            "updatedAt": updated_at
        }

        collection.update_one(
            {"id": banner_id},
            {"$set": update_data},
            upsert=True
        )

        return {
            "id": banner_id,
            **update_data
        }
        
    @classmethod
    def get_all_banners(cls):
        banners = list(collection.find({}, {"_id": 0}))
        return banners