import os, json, ssl, urllib.request, csv
from datetime import datetime

API_KEY = "12f9fb83-8bfc-420f-a136-6981747af8de"
BASE_URL = "https://api.easy-orders.net/api/v1/external-apps"
DATA_DIR = os.path.dirname(os.path.abspath(__file__))
ORDERS_CSV = os.path.join(DATA_DIR, "orders.csv")

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

HEADERS = {
    "Api-Key": API_KEY,
    "Content-Type": "application/json"
}

def fetch_order_by_short_id(short_id):
    url = f"{BASE_URL}/orders/short/{short_id}"
    req = urllib.request.Request(url, headers=HEADERS)
    try:
        with urllib.request.urlopen(req, context=ctx, timeout=6) as resp:
            if resp.status == 200:
                return json.loads(resp.read().decode('utf-8'))
    except Exception as e:
        pass
    return None

def fetch_order_by_uuid(order_uuid):
    url = f"{BASE_URL}/orders/{order_uuid}"
    req = urllib.request.Request(url, headers=HEADERS)
    try:
        with urllib.request.urlopen(req, context=ctx, timeout=6) as resp:
            if resp.status == 200:
                return json.loads(resp.read().decode('utf-8'))
    except Exception as e:
        pass
    return None

if __name__ == "__main__":
    print("Testing EasyOrders API Connection...")
    sample = fetch_order_by_short_id(27300)
    if sample:
        print(f"Success! Order 27300 customer: {sample.get('full_name')} at {sample.get('created_at')}")
    else:
        print("Failed to fetch test order.")
