"""
Migration v3: xóa field shippingRates khỏi tất cả sản phẩm.

Thay đổi:
  - $unset shippingRates — field này không còn dùng,
    thông tin shipping đã nằm trong variants[].shipping
"""

from pymongo import MongoClient

MONGO_URI = "mongodb://localhost:27017/"
DB_NAME = "ecommerce_db"

client = MongoClient(MONGO_URI)
collection = client[DB_NAME]["products"]


def migrate():
    products = list(collection.find({"shippingRates": {"$exists": True}}))
    total_with_field = len(products)

    if total_with_field == 0:
        print("Không có sản phẩm nào còn field shippingRates. Không cần migrate.")
        return

    print(f"Tìm thấy {total_with_field} sản phẩm còn field shippingRates.\n")

    updated = 0
    errors = 0

    for product in products:
        pid = product.get("productId", str(product["_id"]))
        try:
            collection.update_one(
                {"_id": product["_id"]},
                {"$unset": {"shippingRates": ""}}
            )
            updated += 1
            print(f"  [OK] {pid}")
        except Exception as e:
            errors += 1
            print(f"  [ERR] {pid}: {e}")

    print(f"\nXong: {updated}/{total_with_field} sản phẩm đã xóa shippingRates.", end="")
    if errors:
        print(f" {errors} lỗi.")
    else:
        print()


if __name__ == "__main__":
    total = collection.count_documents({})
    print(f"Tổng số sản phẩm trong DB: {total}")
    migrate()
