import json
import os
import threading
import time
import urllib.request
from http.server import ThreadingHTTPServer
import database as db
import server

TEST_DB = os.path.join(db.BASE_DIR, "test_crud_verify.db")


def req(method, url, body=None):
    data = json.dumps(body).encode("utf-8") if body is not None else None
    headers = {"Content-Type": "application/json"} if body is not None else {}
    r = urllib.request.Request(url, data=data, headers=headers, method=method)
    with urllib.request.urlopen(r, timeout=5) as resp:
        return resp.status, json.loads(resp.read().decode("utf-8"))


def run_all_tests():
    if os.path.exists(TEST_DB):
        os.remove(TEST_DB)
    db.DB_PATH = TEST_DB
    db.init_db(TEST_DB)

    httpd = ThreadingHTTPServer(("127.0.0.1", 0), server.PosApiHandler)
    port = httpd.server_address[1]
    base = f"http://127.0.0.1:{port}"
    t = threading.Thread(target=httpd.serve_forever, daemon=True)
    t.start()
    time.sleep(0.2)

    results = []
    try:
        # 1. Health & Initial State Read
        st, h = req("GET", f"{base}/api/health")
        assert st == 200 and h["status"] == "ok" and h["database"] == "SQLite3"
        results.append(("DB Health & Connection", "PASS"))

        st, full = req("GET", f"{base}/api/state")
        assert st == 200 and len(full["products"]) >= 8 and len(full["customers"]) >= 4 and len(full["staff"]) >= 4
        results.append(("Read Initial Seeded State (14 SQLite Tables)", "PASS"))

        # 2. Products CRUD (Create -> Read -> Update -> Delete)
        st, prod = req("POST", f"{base}/api/products", {
            "sku": "TEST-901", "name": "SQA Test Product", "category": "General Retail",
            "price": 1200, "cost": 800, "stock": 25, "taxRate": 18
        })
        assert st == 201 and prod["sku"] == "TEST-901"
        pid = prod["id"]

        st, upd = req("PUT", f"{base}/api/products/{pid}", {"price": 1500, "stock": 30})
        assert st == 200 and upd["price"] == 1500 and upd["stock"] == 30

        st, dl = req("DELETE", f"{base}/api/products/{pid}")
        assert st == 200 and dl["deleted"] is True
        results.append(("Products & Stock CRUD (POST/GET/PUT/DELETE)", "PASS"))

        # 3. Customers & Suppliers CRUD (Create -> Update -> Delete)
        st, cust = req("POST", f"{base}/api/contacts", {
            "contactType": "customer", "name": "SQA Client Corp", "phone": "0300-1112223",
            "dueBalance": 5000, "creditLimit": 100000, "payTerms": 15
        })
        assert st == 201 and cust["due_balance"] == 5000
        cid = cust["id"]

        st, cupd = req("PUT", f"{base}/api/contacts/{cid}", {"name": "SQA Client Updated", "dueBalance": 7500})
        assert st == 200 and cupd["name"] == "SQA Client Updated" and cupd["due_balance"] == 7500
        results.append(("Customers & Suppliers CRUD (Create & Update)", "PASS"))

        # 4. Atomic POS Checkout -> FBR Invoice + Stock Deduction + Customer Previous Balance Update + SQL Report
        st, before_prods = req("GET", f"{base}/api/products")
        p1_before = next(x for x in before_prods if x["id"] == "p1")["stock"]

        st, inv = req("POST", f"{base}/api/invoices", {
            "usin": "INV-2026-9991", "customerId": cid, "buyerName": "SQA Client Updated",
            "subtotal": 5000, "netSaleValue": 5000, "totalTax": 900, "posFee": 1,
            "grandTotal": 5901, "paidAmount": 3000, "totalQty": 2,
            "items": [{
                "id": "p1", "sku": "ITEM-101", "name": "Premium Retail Product A", "category": "General Retail",
                "pctCode": "99990000", "qty": 2, "price": 2500, "cost": 1700, "taxRate": 18,
                "saleValue": 5000, "taxAmount": 900, "lineTotal": 5900
            }]
        })
        # Prev balance was 7500 + 5901 bill = 13401 total - 3000 paid = 10401 closing balance
        assert st == 201 and inv["previous_balance"] == 7500 and inv["closing_balance"] == 10401
        st, after_prods = req("GET", f"{base}/api/products")
        p1_after = next(x for x in after_prods if x["id"] == "p1")["stock"]
        assert p1_after == p1_before - 2

        st, crep = req("GET", f"{base}/api/reports/customer/{cid}")
        assert st == 200 and len(crep["invoices"]) == 1 and len(crep["productsBought"]) == 1
        results.append(("Atomic POS Checkout + Stock Deduction + Khata Prev->Closing Balance + SQL Report", "PASS"))

        st, cdel = req("DELETE", f"{base}/api/contacts/{cid}")
        assert st == 200 and cdel["deleted"] is True
        results.append(("Contact Delete CRUD", "PASS"))

        # 5. Users & RBAC CRUD
        st, usr = req("POST", f"{base}/api/users", {
            "name": "SQA Cashier", "username": "sqacashier", "password": "secret",
            "role": "Cashier", "salary": 40000, "perms": ["pos", "templates"]
        })
        assert st == 201 and usr["username"] == "sqacashier"
        uid = usr["id"]

        st, uupd = req("PUT", f"{base}/api/users/{uid}", {"active": False, "role": "Manager"})
        assert st == 200 and uupd["active"] == 0 and uupd["role"] == "Manager"

        st, udel = req("DELETE", f"{base}/api/users/{uid}")
        assert st == 200 and udel["deleted"] is True
        results.append(("Users & RBAC CRUD (POST/PUT/DELETE)", "PASS"))

        # 6. Standard Template Save & Read
        st, tpl_res = req("PUT", f"{base}/api/template", {
            "companyName": "SQA Custom Co.", "accent": "#4f46e5", "layout": "a4_modern",
            "logoDataUrl": "data:image/png;base64,iVBORw0KGgo=", "showPrevBal": True
        })
        assert st == 200 and tpl_res["ok"] is True
        st, tpl_get = req("GET", f"{base}/api/template")
        assert st == 200 and tpl_get["companyName"] == "SQA Custom Co."
        results.append(("Standard Template Persistence (PUT/GET SQLite)", "PASS"))

        # 7. Full State Sync Roundtrip (Bills, Quotations, Purchases, Expenses, AI Workflows)
        st, state_now = req("GET", f"{base}/api/state")
        state_now["bills"].insert(0, {
            "id": "BILL-SQA-1", "date": "2026-11-20", "party": "Test Vendor",
            "desc": "SQA Utility Bill", "amount": 5000, "taxRate": 18, "taxAmount": 900,
            "total": 5900, "dueDate": "2026-12-01", "status": "Unpaid"
        })
        st, sync_res = req("POST", f"{base}/api/sync", state_now)
        assert st == 200 and sync_res["ok"] is True
        st, bills_after = req("GET", f"{base}/api/bills")
        assert any(b["id"] == "BILL-SQA-1" for b in bills_after)
        results.append(("Full Relational State Sync (Bills/Quotes/Purchases/Workflows)", "PASS"))

        print("=== SQLITE DATABASE & REST API CRUD VERIFICATION REPORT ===")
        for name, status in results:
            print(f"[ {status} ] {name}")
        print(f"TOTAL: {len(results)}/{len(results)} PASSED (100%)")
    finally:
        httpd.shutdown()
        if os.path.exists(TEST_DB):
            os.remove(TEST_DB)


if __name__ == "__main__":
    run_all_tests()
