# PocketBase Collection Creation Script
# Create all collections needed for a Firebase migration.
# Run from the Docker host: python3 create_collections.py

import urllib.request
import json

BASE = "http://127.0.0.1:8091"
EMAIL = "admin@example.com"
PASS = "your-admin-password"

def api(method, path, data=None, token=None):
    headers = {"Content-Type": "application/json"}
    if token: headers["Authorization"] = token
    req = urllib.request.Request(f"{BASE}{path}",
        data=json.dumps(data).encode() if data else None,
        headers=headers, method=method)
    try:
        resp = urllib.request.urlopen(req)
        return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        body = e.read().decode()
        if "exists" in body.lower() or "unique" in body.lower():
            return None  # Already exists, OK
        print(f"  ERROR {method} {path}: HTTP {e.code} — {body[:300]}")
        return None

# Auth
auth = api("POST", "/api/collections/_superusers/auth-with-password",
    {"identity": EMAIL, "password": PASS})
token = auth["token"]

# Define your collections — add our app's collections
COLLECTIONS = [
    ("repairOrders", [{"name": "userId", "type": "text", "required": True}]),
    ("appointments", [{"name": "userId", "type": "text", "required": True}]),
    ("quotes", [{"name": "userId", "type": "text", "required": True}]),
    ("tasks", [{"name": "userId", "type": "text", "required": True}]),
    ("services", [{"name": "userId", "type": "text", "required": True}]),
    ("customers", [{"name": "userId", "type": "text", "required": True}]),
    ("settings", [
        {"name": "userId", "type": "text", "required": True},
        {"name": "name", "type": "text", "required": True},
    ]),
]

# Create collections (empty rules first — rules fail if they reference fields before schema exists)
for name, schema in COLLECTIONS:
    result = api("POST", "/api/collections", {
        "name": name, "type": "base", "schema": schema,
        "listRule": "", "viewRule": "", "createRule": "",
        "updateRule": "", "deleteRule": ""
    }, token)
    if result: print(f"Created: {name}")
    else: print(f"Skipped: {name} (exists or error)")

print("Done!")
