"""Generate the Postman collection JSON for Rfoof API."""
import json

collection = {
    "info": {
        "_postman_id": "rfoof-collection-001",
        "name": "Rfoof API",
        "description": "Rofoof Shopping Marketplace API - UAE.\n\nFirebase Phone Auth → JWT. Supports English/Arabic via Accept-Language header.\n\nAuth: Bearer token in Authorization header.\nLocalization: Accept-Language: en | ar",
        "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
    },
    "auth": {
        "type": "bearer",
        "bearer": [{"key": "token", "value": "{{access_token}}", "type": "string"}],
    },
    "event": [
        {
            "listen": "prerequest",
            "script": {
                "type": "text/javascript",
                "exec": [""],
            },
        }
    ],
    "variable": [],
    "item": [],
}


def req(method, path, *, auth="inherit", headers=None, body=None, query=None, description=""):
    """Helper to build a request object."""
    hdrs = headers or []
    r = {
        "method": method,
        "header": hdrs,
        "url": {
            "raw": "{{base_url}}/" + path.lstrip("/"),
            "host": ["{{base_url}}"],
            "path": [p for p in path.strip("/").split("/") if p] + [""],
        },
    }
    if query:
        r["url"]["query"] = query
        r["url"]["raw"] += "?" + "&".join(f"{q['key']}={q['value']}" for q in query if not q.get("disabled"))
    if body:
        r["body"] = body
    if auth == "noauth":
        r["auth"] = {"type": "noauth"}
    if description:
        r["description"] = description
    return r


def item(name, request, events=None):
    """Helper to build an item."""
    i = {"name": name, "request": request}
    if events:
        i["event"] = events
    return i


def lang_header():
    return {"key": "Accept-Language", "value": "{{language}}"}


def json_header():
    return {"key": "Content-Type", "value": "application/json"}


def json_body(raw):
    return {"mode": "raw", "raw": raw}


def form_body(fields):
    return {"mode": "formdata", "formdata": fields}


def save_tokens_script():
    return [
        {
            "listen": "test",
            "script": {
                "type": "text/javascript",
                "exec": [
                    "var jsonData = pm.response.json();",
                    "if (jsonData.data && jsonData.data.access) {",
                    "    pm.environment.set('access_token', jsonData.data.access);",
                    "    pm.environment.set('refresh_token', jsonData.data.refresh);",
                    "}",
                ],
            },
        }
    ]


def save_tokens_direct_script():
    return [
        {
            "listen": "test",
            "script": {
                "type": "text/javascript",
                "exec": [
                    "var jsonData = pm.response.json();",
                    "var d = jsonData.data || jsonData;",
                    "if (d.access) {",
                    "    pm.environment.set('access_token', d.access);",
                    "}",
                    "if (d.refresh) {",
                    "    pm.environment.set('refresh_token', d.refresh);",
                    "}",
                ],
            },
        }
    ]


# ============================================================
# AUTH
# ============================================================
auth_folder = {
    "name": "Auth",
    "item": [
        item(
            "Firebase Login",
            req("POST", "auth/firebase/", auth="noauth", headers=[json_header(), lang_header()],
                body=json_body('{\n  "id_token": "{{firebase_id_token}}"\n}')),
            events=save_tokens_script(),
        ),
        item(
            "Refresh Token",
            req("POST", "auth/refresh/", auth="noauth", headers=[json_header()],
                body=json_body('{\n  "refresh": "{{refresh_token}}"\n}')),
            events=save_tokens_direct_script(),
        ),
        item("Logout", req("POST", "auth/logout/", headers=[json_header(), lang_header()],
                           body=json_body('{\n  "refresh": "{{refresh_token}}"\n}'))),
        item("Get Profile (me)", req("GET", "auth/me/", headers=[lang_header()])),
        item("Update Profile (me)", req("PATCH", "auth/me/", headers=[json_header(), lang_header()],
                                        body=json_body('{\n  "full_name": "John Doe",\n  "email": "john@example.com",\n  "language": "en",\n  "customer_type": "customer",\n  "notifications_enabled": true\n}'))),
        item("Delete Account (me)", req("DELETE", "auth/me/", headers=[lang_header()])),
        item("Check App Review Status", req("GET", "auth/app-review/")),
        item("Mark App Reviewed", req("POST", "auth/app-review/")),
    ],
}

# ============================================================
# ADMIN AUTH (DJOSER)
# ============================================================
admin_auth_folder = {
    "name": "Admin Auth (Djoser)",
    "item": [
        item("Admin JWT Login", req("POST", "auth/admin/jwt/create/", auth="noauth",
                                    headers=[json_header()],
                                    body=json_body('{\n  "email": "{{admin_email}}",\n  "password": "{{admin_password}}"\n}')),
             events=save_tokens_direct_script()),
        item("Admin JWT Refresh", req("POST", "auth/admin/jwt/refresh/", auth="noauth",
                                      headers=[json_header()],
                                      body=json_body('{\n  "refresh": "{{refresh_token}}"\n}')),
             events=save_tokens_direct_script()),
    ],
}

# ============================================================
# CORE
# ============================================================
core_folder = {
    "name": "Core",
    "item": [
        item("Health Check", req("GET", "health/", auth="noauth")),
        item("Home Feed (Guest)", req("GET", "home/guest/", auth="noauth", headers=[lang_header()])),
        item("Home Feed (Authenticated)", req("GET", "home/", headers=[lang_header()])),
        item("Global Search", req("GET", "search/", auth="noauth", headers=[lang_header()],
                                  query=[{"key": "q", "value": "coffee"}])),
        item("App Version Check", req("GET", "app-version/", auth="noauth", headers=[lang_header()],
                                      query=[{"key": "platform", "value": "ios"}])),
        item("App Version Update (Admin)", req("PUT", "app-version/update/", headers=[json_header()],
                                               body=json_body('{\n  "platform": "ios",\n  "latest_version": "2.0.0",\n  "minimum_version": "1.5.0",\n  "is_force_update": false,\n  "update_url": "https://apps.apple.com/app/rfoof",\n  "release_notes_en": "Bug fixes",\n  "release_notes_ar": "إصلاح أخطاء"\n}'))),
        item("About Page", req("GET", "about/", auth="noauth", headers=[lang_header()])),
        item("About Page Update (Admin)", req("PUT", "about/update_about/", headers=[json_header()],
                                              body=json_body('{\n  "content_en": "About Rofoof...",\n  "content_ar": "حول رفوف...",\n  "version_label": "1.0.0",\n  "build_info": "Build 100",\n  "copyright_text": "© 2024 Rofoof"\n}'))),
        item("Terms & Conditions", req("GET", "terms/", auth="noauth", headers=[lang_header()])),
        item("Terms Update (Admin)", req("PUT", "terms/update/", headers=[json_header()],
                                         body=json_body('{\n  "content_en": "Terms and Conditions...",\n  "content_ar": "الشروط والأحكام...",\n  "version_label": "1.0"\n}'))),
        item("Support Contact", req("GET", "support/", auth="noauth")),
        item("Support Contact Update (Admin)", req("PUT", "support/update_contact/", headers=[json_header()],
                                                   body=json_body('{\n  "whatsapp_number": "+971501234567",\n  "instagram_handle": "@rfoof",\n  "chat_url": "https://chat.rfoof.online",\n  "phone_number": "+971501234567",\n  "email": "support@rfoof.online"\n}'))),
    ],
}

# ============================================================
# BANNERS
# ============================================================
banners_folder = {
    "name": "Banners",
    "item": [
        item("List Banners", req("GET", "banners/", auth="noauth", headers=[lang_header()],
                                 query=[
                                     {"key": "placement", "value": "home_top", "disabled": True},
                                     {"key": "is_active", "value": "true", "disabled": True},
                                     {"key": "search", "value": "", "disabled": True},
                                     {"key": "ordering", "value": "display_order", "disabled": True},
                                 ])),
        item("Get Banner", req("GET", "banners/{{banner_id}}", auth="noauth", headers=[lang_header()])),
        item("Create Banner (Admin)", req("POST", "banners/", headers=[],
                                          body=form_body([
                                              {"key": "title_en", "value": "Big Sale", "type": "text"},
                                              {"key": "title_ar", "value": "تخفيضات كبيرة", "type": "text"},
                                              {"key": "subtitle_en", "value": "Up to 50% off", "type": "text"},
                                              {"key": "subtitle_ar", "value": "خصم يصل إلى 50%", "type": "text"},
                                              {"key": "cta_text_en", "value": "Shop Now", "type": "text"},
                                              {"key": "cta_text_ar", "value": "تسوق الآن", "type": "text"},
                                              {"key": "cta_url", "value": "https://rfoof.online/sale", "type": "text"},
                                              {"key": "placement", "value": "home_top", "type": "text"},
                                              {"key": "display_order", "value": "1", "type": "text"},
                                              {"key": "is_active", "value": "true", "type": "text"},
                                              {"key": "image", "type": "file", "src": ""},
                                          ]))),
        item("Update Banner (Admin)", req("PATCH", "banners/{{banner_id}}", headers=[json_header()],
                                          body=json_body('{\n  "title_en": "Updated Banner",\n  "is_active": true\n}'))),
        item("Delete Banner (Admin)", req("DELETE", "banners/{{banner_id}}")),
    ],
}

# ============================================================
# CATEGORIES
# ============================================================
categories_folder = {
    "name": "Categories",
    "item": [
        item("List Categories", req("GET", "categories/", auth="noauth", headers=[lang_header()])),
        item("Get Category", req("GET", "categories/{{category_id}}", auth="noauth", headers=[lang_header()])),
        item("Category Stores", req("GET", "categories/{{category_id}}/stores/", auth="noauth", headers=[lang_header()])),
        item("Create Category (Admin)", req("POST", "categories/", headers=[],
                                            body=form_body([
                                                {"key": "name_en", "value": "Electronics", "type": "text"},
                                                {"key": "name_ar", "value": "إلكترونيات", "type": "text"},
                                                {"key": "icon", "type": "file", "src": ""},
                                            ]))),
        item("Update Category (Admin)", req("PATCH", "categories/{{category_id}}", headers=[json_header()],
                                            body=json_body('{\n  "name_en": "Updated Category"\n}'))),
        item("Delete Category (Admin)", req("DELETE", "categories/{{category_id}}")),
    ],
}

# ============================================================
# STORES
# ============================================================
stores_folder = {
    "name": "Stores",
    "item": [
        item("List Stores", req("GET", "stores/", auth="noauth", headers=[lang_header()],
                                query=[
                                    {"key": "search", "value": "", "disabled": True},
                                    {"key": "category", "value": "", "disabled": True},
                                    {"key": "is_online", "value": "true", "disabled": True},
                                    {"key": "is_in_store", "value": "true", "disabled": True},
                                    {"key": "has_deals", "value": "true", "disabled": True},
                                    {"key": "ordering", "value": "-created_at", "disabled": True},
                                    {"key": "page", "value": "1", "disabled": True},
                                ])),
        item("Get Store", req("GET", "stores/{{store_id}}", auth="noauth", headers=[lang_header()])),
        item("Top Stores", req("GET", "stores/top/", auth="noauth", headers=[lang_header()])),
        item("Recommended Stores", req("GET", "stores/recommended/", auth="noauth", headers=[lang_header()])),
        item("Recently Added Stores", req("GET", "stores/recently-added/", auth="noauth", headers=[lang_header()])),
        item("My Stores", req("GET", "stores/mine/", headers=[lang_header()])),
        item("Create Store", req("POST", "stores/", headers=[],
                                 body=form_body([
                                     {"key": "name_en", "value": "My Store", "type": "text"},
                                     {"key": "name_ar", "value": "متجري", "type": "text"},
                                     {"key": "description_en", "value": "A great store", "type": "text"},
                                     {"key": "description_ar", "value": "متجر رائع", "type": "text"},
                                     {"key": "whatsapp_link", "value": "https://wa.me/971501234567", "type": "text"},
                                     {"key": "instagram_link", "value": "https://instagram.com/mystore", "type": "text"},
                                     {"key": "is_online", "value": "true", "type": "text"},
                                     {"key": "is_in_store", "value": "false", "type": "text"},
                                     {"key": "local_delivery_days", "value": "3", "type": "text"},
                                     {"key": "intl_delivery_days", "value": "7", "type": "text"},
                                     {"key": "categories", "value": "1", "type": "text"},
                                     {"key": "logo", "type": "file", "src": ""},
                                     {"key": "cover", "type": "file", "src": ""},
                                 ]))),
        item("Update Store", req("PATCH", "stores/{{store_id}}", headers=[json_header()],
                                 body=json_body('{\n  "name_en": "Updated Store Name",\n  "description_en": "Updated description"\n}'))),
        item("Delete Store", req("DELETE", "stores/{{store_id}}")),
        item("List Branches", req("GET", "stores/{{store_id}}/branches/", auth="noauth")),
        item("Add Branch", req("POST", "stores/{{store_id}}/branches/", headers=[json_header()],
                               body=json_body('{\n  "address": "Dubai Mall, Ground Floor",\n  "latitude": 25.1972,\n  "longitude": 55.2796,\n  "is_open": true,\n  "open_hours": "9:00 AM - 10:00 PM"\n}'))),
        item("Update Branch", req("PUT", "stores/{{store_id}}/branches/{{branch_id}}", headers=[json_header()],
                                  body=json_body('{\n  "address": "Updated Address",\n  "latitude": 25.1972,\n  "longitude": 55.2796,\n  "is_open": true,\n  "open_hours": "10:00 AM - 9:00 PM"\n}'))),
        item("Delete Branch", req("DELETE", "stores/{{store_id}}/branches/{{branch_id}}")),
        item("List Reviews", req("GET", "stores/{{store_id}}/reviews/", auth="noauth", headers=[lang_header()])),
        item("Submit Review", req("POST", "stores/{{store_id}}/reviews/", headers=[json_header()],
                                  body=json_body('{\n  "rating": 5,\n  "title": "Great store!",\n  "comment": "Loved the products and fast delivery."\n}'))),
    ],
}

# ============================================================
# PRODUCTS
# ============================================================
products_folder = {
    "name": "Products",
    "item": [
        item("List Products", req("GET", "products/", auth="noauth", headers=[lang_header()],
                                  query=[
                                      {"key": "store", "value": "", "disabled": True},
                                      {"key": "category", "value": "", "disabled": True},
                                      {"key": "is_featured", "value": "true", "disabled": True},
                                      {"key": "has_discount", "value": "true", "disabled": True},
                                      {"key": "min_price", "value": "", "disabled": True},
                                      {"key": "max_price", "value": "", "disabled": True},
                                      {"key": "search", "value": "", "disabled": True},
                                      {"key": "ordering", "value": "-created_at", "disabled": True},
                                      {"key": "page", "value": "1", "disabled": True},
                                  ])),
        item("Get Product", req("GET", "products/{{product_id}}", auth="noauth", headers=[lang_header()])),
        item("Great Offers", req("GET", "products/great-offers/", auth="noauth", headers=[lang_header()])),
        item("My Products", req("GET", "products/mine/", headers=[lang_header()])),
        item("Create Product", req("POST", "products/", headers=[],
                                   body=form_body([
                                       {"key": "store", "value": "{{store_id}}", "type": "text"},
                                       {"key": "category", "value": "{{category_id}}", "type": "text"},
                                       {"key": "name_en", "value": "Product Name", "type": "text"},
                                       {"key": "name_ar", "value": "اسم المنتج", "type": "text"},
                                       {"key": "description_en", "value": "Product description", "type": "text"},
                                       {"key": "description_ar", "value": "وصف المنتج", "type": "text"},
                                       {"key": "price", "value": "99.99", "type": "text"},
                                       {"key": "original_price", "value": "149.99", "type": "text"},
                                       {"key": "discount_percent", "value": "33", "type": "text"},
                                       {"key": "is_featured", "value": "false", "type": "text"},
                                       {"key": "image", "type": "file", "src": ""},
                                   ]))),
        item("Update Product", req("PATCH", "products/{{product_id}}", headers=[json_header()],
                                   body=json_body('{\n  "name_en": "Updated Product",\n  "price": 79.99\n}'))),
        item("Delete Product", req("DELETE", "products/{{product_id}}")),
    ],
}

# ============================================================
# EVENTS
# ============================================================
events_folder = {
    "name": "Events",
    "item": [
        item("List Events", req("GET", "events/", auth="noauth", headers=[lang_header()],
                                query=[
                                    {"key": "search", "value": "", "disabled": True},
                                    {"key": "is_active", "value": "true", "disabled": True},
                                    {"key": "start_date_after", "value": "2024-01-01", "disabled": True},
                                    {"key": "start_date_before", "value": "2025-12-31", "disabled": True},
                                    {"key": "ordering", "value": "-start_date", "disabled": True},
                                ])),
        item("Get Event", req("GET", "events/{{event_id}}", auth="noauth", headers=[lang_header()])),
        item("Event Stores", req("GET", "events/{{event_id}}/stores/", auth="noauth", headers=[lang_header()],
                                 query=[{"key": "search", "value": "", "disabled": True}])),
        item("Create Event (Admin)", req("POST", "events/", headers=[],
                                         body=form_body([
                                             {"key": "name_en", "value": "Summer Sale Event", "type": "text"},
                                             {"key": "name_ar", "value": "حدث التخفيضات الصيفية", "type": "text"},
                                             {"key": "description_en", "value": "Annual summer sale", "type": "text"},
                                             {"key": "description_ar", "value": "تخفيضات الصيف السنوية", "type": "text"},
                                             {"key": "start_date", "value": "2025-06-01", "type": "text"},
                                             {"key": "end_date", "value": "2025-06-30", "type": "text"},
                                             {"key": "venue_name", "value": "Dubai Mall", "type": "text"},
                                             {"key": "address", "value": "Dubai, UAE", "type": "text"},
                                             {"key": "latitude", "value": "25.1972", "type": "text"},
                                             {"key": "longitude", "value": "55.2796", "type": "text"},
                                             {"key": "cover", "type": "file", "src": ""},
                                             {"key": "logo", "type": "file", "src": ""},
                                         ]))),
        item("Update Event (Admin)", req("PATCH", "events/{{event_id}}", headers=[json_header()],
                                         body=json_body('{\n  "name_en": "Updated Event"\n}'))),
        item("Delete Event (Admin)", req("DELETE", "events/{{event_id}}")),
    ],
}

# ============================================================
# ENGAGEMENT (Favorites, Recently Viewed, Coupons, Notifications)
# ============================================================
engagement_folder = {
    "name": "Engagement",
    "item": [
        # Favorites
        item("List Favorites", req("GET", "favorites/", headers=[lang_header()],
                                   query=[
                                       {"key": "search", "value": "", "disabled": True},
                                       {"key": "deals", "value": "true", "disabled": True},
                                       {"key": "installments", "value": "true", "disabled": True},
                                       {"key": "online", "value": "true", "disabled": True},
                                       {"key": "in_store", "value": "true", "disabled": True},
                                   ])),
        item("Add Favorite", req("POST", "favorites/", headers=[json_header()],
                                 body=json_body('{\n  "store_id": {{store_id}}\n}'))),
        item("Remove Favorite", req("DELETE", "favorites/{{store_id}}")),
        # Recently Viewed
        item("List Recently Viewed", req("GET", "recently-viewed/", headers=[lang_header()])),
        item("Record Store View", req("POST", "recently-viewed/", headers=[json_header()],
                                      body=json_body('{\n  "store_id": {{store_id}}\n}'))),
        # Coupons
        item("List Coupons", req("GET", "coupons/", auth="noauth", headers=[lang_header()],
                                 query=[
                                     {"key": "store", "value": "{{store_id}}", "disabled": True},
                                 ])),
        item("Get Coupon", req("GET", "coupons/{{coupon_id}}", auth="noauth", headers=[lang_header()])),
        item("Create Coupon (Admin)", req("POST", "coupons/", headers=[json_header()],
                                          body=json_body('{\n  "code": "SUMMER2025",\n  "discount_percent": 20,\n  "discount_amount": null,\n  "valid_from": "2025-06-01T00:00:00Z",\n  "valid_until": "2025-08-31T23:59:59Z",\n  "store": {{store_id}},\n  "is_active": true\n}'))),
        item("Update Coupon (Admin)", req("PATCH", "coupons/{{coupon_id}}", headers=[json_header()],
                                          body=json_body('{\n  "is_active": false\n}'))),
        item("Delete Coupon (Admin)", req("DELETE", "coupons/{{coupon_id}}")),
        # Notifications
        item("List Notifications", req("GET", "notifications/", headers=[lang_header()])),
        item("Unread Count", req("GET", "notifications/unread-count/")),
        item("Mark as Read", req("PATCH", "notifications/{{notification_id}}/read/")),
        item("Mark All as Read", req("PATCH", "notifications/read-all/")),
        item("Notification Settings", req("PATCH", "notifications/settings/", headers=[json_header()],
                                          body=json_body('{\n  "notifications_enabled": true\n}'))),
        item("Create Notification (Admin)", req("POST", "notifications/", headers=[json_header()],
                                                body=json_body('{\n  "user": 1,\n  "title": "Welcome!",\n  "body": "Thanks for joining Rofoof",\n  "type": "general",\n  "image": null\n}'))),
    ],
}

# ============================================================
# REFERRALS
# ============================================================
referrals_folder = {
    "name": "Referrals",
    "item": [
        item("My Referral Code", req("GET", "referrals/my-code/")),
        item("Apply Referral Code", req("POST", "referrals/apply/", headers=[json_header()],
                                        body=json_body('{\n  "code": "ABC123"\n}'))),
        item("Referral History", req("GET", "referrals/history/")),
        item("Points Balance", req("GET", "referrals/points/")),
        item("List All Referrals (Admin)", req("GET", "admin/referrals/")),
        item("Get Referral (Admin)", req("GET", "admin/referrals/1/")),
    ],
}

# ============================================================
# PROMOTIONS
# ============================================================
promotions_folder = {
    "name": "Promotions",
    "item": [
        item("List Promotion Plans", req("GET", "promotion-plans/", auth="noauth", headers=[lang_header()])),
        item("Get Promotion Plan", req("GET", "promotion-plans/{{promotion_plan_id}}", auth="noauth", headers=[lang_header()])),
        item("Create Promotion Plan (Admin)", req("POST", "promotion-plans/", headers=[json_header()],
                                                   body=json_body('{\n  "name_en": "Gold Store Plan",\n  "name_ar": "خطة المتجر الذهبية",\n  "type": "store",\n  "duration_months": 3,\n  "price": 299.00,\n  "is_active": true\n}'))),
        item("Update Promotion Plan (Admin)", req("PATCH", "promotion-plans/{{promotion_plan_id}}", headers=[json_header()],
                                                   body=json_body('{\n  "price": 249.00\n}'))),
        item("Delete Promotion Plan (Admin)", req("DELETE", "promotion-plans/{{promotion_plan_id}}")),
        item("List My Promotions", req("GET", "promotions/mine/")),
        item("Create Promotion", req("POST", "promotions/", headers=[json_header()],
                                     body=json_body('{\n  "store": {{store_id}},\n  "product": null,\n  "plan": {{promotion_plan_id}}\n}'),
                                     description="Creates a promotion (pending) and returns a MyFatoorah payment_url. Redirect user there to pay.")),
        item("Confirm Payment", req("POST", "promotions/{{promotion_id}}/confirm-payment/",
                                    description="Call after user completes payment on MyFatoorah. Activates the promotion.")),
        item("List All Promotions (Admin)", req("GET", "promotions/")),
    ],
}

# ============================================================
# ANALYTICS
# ============================================================
analytics_folder = {
    "name": "Analytics",
    "item": [
        item("Track Single Event", req("POST", "analytics/track/", headers=[json_header()],
                                       body=json_body('{\n  "event_type": "screen_view",\n  "event_name": "home_opened",\n  "screen_name": "home",\n  "target_type": "",\n  "target_id": "",\n  "target_name": "",\n  "metadata": {},\n  "session_id": "sess_abc123",\n  "session_duration": null,\n  "platform": "ios",\n  "app_version": "1.2.0",\n  "os_version": "17.5",\n  "device_model": "iPhone 15",\n  "screen_resolution": "1179x2556",\n  "device_id": "device_uuid_here",\n  "latitude": 25.1972,\n  "longitude": 55.2796,\n  "city": "Dubai",\n  "country": "AE",\n  "connection_type": "wifi",\n  "client_timestamp": "2025-06-21T10:30:00Z"\n}'),
                                       description="Send a single user behavior event. Works for both authenticated and guest users.")),
        item("Track Batch Events", req("POST", "analytics/batch/", headers=[json_header()],
                                       body=json_body('{\n  "events": [\n    {\n      "event_type": "screen_view",\n      "screen_name": "home",\n      "device_id": "device_uuid_here",\n      "session_id": "sess_abc123",\n      "platform": "ios",\n      "app_version": "1.2.0",\n      "client_timestamp": "2025-06-21T10:30:00Z"\n    },\n    {\n      "event_type": "store_view",\n      "screen_name": "store_detail",\n      "target_type": "store",\n      "target_id": "5",\n      "target_name": "Coffee House",\n      "device_id": "device_uuid_here",\n      "session_id": "sess_abc123",\n      "platform": "ios",\n      "app_version": "1.2.0",\n      "client_timestamp": "2025-06-21T10:31:00Z"\n    },\n    {\n      "event_type": "favorite_add",\n      "screen_name": "store_detail",\n      "target_type": "store",\n      "target_id": "5",\n      "device_id": "device_uuid_here",\n      "session_id": "sess_abc123",\n      "platform": "ios",\n      "app_version": "1.2.0",\n      "client_timestamp": "2025-06-21T10:31:30Z"\n    }\n  ]\n}'),
                                       description="Send multiple events at once (recommended for performance). Batch up events and send periodically.")),
        item("Report Session", req("POST", "analytics/session/", headers=[json_header()],
                                   body=json_body('{\n  "session_id": "sess_abc123",\n  "device_id": "device_uuid_here",\n  "started_at": "2025-06-21T10:30:00Z",\n  "ended_at": "2025-06-21T10:45:00Z",\n  "duration_seconds": 900,\n  "platform": "ios",\n  "app_version": "1.2.0",\n  "device_model": "iPhone 15",\n  "screens_viewed": 8,\n  "events_count": 23\n}'),
                                   description="Report a session start or end. Send again with ended_at to close the session.")),
        item("List Events (Admin)", req("GET", "admin/analytics/events/", headers=[lang_header()],
                                        query=[
                                            {"key": "user", "value": "", "disabled": True},
                                            {"key": "event_type", "value": "screen_view", "disabled": True},
                                            {"key": "screen_name", "value": "", "disabled": True},
                                            {"key": "platform", "value": "ios", "disabled": True},
                                            {"key": "target_type", "value": "store", "disabled": True},
                                            {"key": "date_from", "value": "2025-06-01T00:00:00Z", "disabled": True},
                                            {"key": "date_to", "value": "2025-06-30T23:59:59Z", "disabled": True},
                                            {"key": "page", "value": "1", "disabled": True},
                                        ])),
        item("List Sessions (Admin)", req("GET", "admin/analytics/sessions/", headers=[lang_header()],
                                          query=[
                                              {"key": "user", "value": "", "disabled": True},
                                              {"key": "platform", "value": "ios", "disabled": True},
                                              {"key": "date_from", "value": "2025-06-01T00:00:00Z", "disabled": True},
                                              {"key": "date_to", "value": "2025-06-30T23:59:59Z", "disabled": True},
                                              {"key": "min_duration", "value": "60", "disabled": True},
                                              {"key": "page", "value": "1", "disabled": True},
                                          ])),
        item("Dashboard Summary (Admin)", req("GET", "admin/analytics/dashboard/summary/",
                                              description="Overview: total events, sessions, active users, top screens, top events, daily chart.")),
        item("User Activity Timeline (Admin)", req("GET", "admin/analytics/dashboard/user-activity/",
                                                   query=[{"key": "user_id", "value": "1"}],
                                                   description="Full behavior timeline for a specific user.")),
        item("Conversion Funnel (Admin)", req("GET", "admin/analytics/dashboard/funnel/",
                                             query=[{"key": "days", "value": "30", "disabled": True}],
                                             description="Funnel: app_open → store_view → product_view → favorite → whatsapp → share")),
    ],
}

# ============================================================
# ASSEMBLE COLLECTION
# ============================================================
collection["item"] = [
    auth_folder,
    admin_auth_folder,
    core_folder,
    banners_folder,
    categories_folder,
    stores_folder,
    products_folder,
    events_folder,
    engagement_folder,
    referrals_folder,
    promotions_folder,
    analytics_folder,
]

# Write output
output_path = "/home/wahba/Documents/Work/Emirates/rfoof/postman/rfoof_collection.json"
with open(output_path, "w", encoding="utf-8") as f:
    json.dump(collection, f, indent=2, ensure_ascii=False)

print(f"✓ Collection written to {output_path}")
