"""
Giao tiep voi backend API.

GET  /products/pending?username=...   — lay danh sach san pham can xu ly
PATCH /products/:id/done              — danh dau san pham hoan thanh
"""
from __future__ import annotations

import json
import urllib.error
import urllib.request

from .constants import API_BASE_URL


def get_pending_products(username: str) -> list[dict]:
    """Lay danh sach san pham co status = not_start cua user."""
    url = f"{API_BASE_URL}/products/pending?username={username}"
    req = urllib.request.Request(url, headers={"Accept": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            return json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        raise RuntimeError(f"Loi API ({e.code}): {e.reason}") from e
    except Exception as e:
        raise RuntimeError(f"Khong the ket noi API: {e}") from e


def mark_product_done(product_id: int, backend_key: str) -> dict:
    """Danh dau san pham la done sau khi xu ly xong."""
    url = f"{API_BASE_URL}/products/{product_id}/done"
    req = urllib.request.Request(
        url,
        data=b"",
        method="PATCH",
        headers={
            "x-backend-key": backend_key,
            "Content-Length": "0",
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            return json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        if e.code == 401:
            raise RuntimeError("Backend key khong hop le (401 Unauthorized).") from e
        raise RuntimeError(f"Loi API mark done ({e.code}): {e.reason}") from e
    except Exception as e:
        raise RuntimeError(f"Khong the ket noi API: {e}") from e
