"""Shared Shopify Admin API auth and GraphQL for blog services."""

import os
from typing import Any

import requests
from django.conf import settings

from webhooks.models import ShopifyStore


class ShopifyAdminClient:
    """REST/GraphQL helpers used by ShopifyBlogService and ShopifyFileService."""

    @staticmethod
    def shop_domain() -> str:
        domain = (os.getenv("SHOPIFY_STORE") or "").strip()
        if not domain:
            raise RuntimeError("SHOPIFY_STORE not configured")
        return domain

    @classmethod
    def access_token(cls) -> str:
        record = ShopifyStore.objects.filter(shop_domain=cls.shop_domain()).first()
        if not record or not record.access_token:
            raise RuntimeError(f"No Shopify access token for {cls.shop_domain()}")
        return record.access_token

    @classmethod
    def base_url(cls) -> str:
        domain = cls.shop_domain()
        if not domain.startswith("http"):
            domain = f"https://{domain}"
        return domain.rstrip("/")

    @staticmethod
    def api_version() -> str:
        return getattr(settings, "SHOPIFY_API_VERSION", "2024-07")

    @classmethod
    def headers(cls) -> dict[str, str]:
        return {
            "X-Shopify-Access-Token": cls.access_token(),
            "Content-Type": "application/json",
        }

    @classmethod
    def admin_url(cls, path: str) -> str:
        return f"{cls.base_url()}/admin/api/{cls.api_version()}/{path.lstrip('/')}"

    @classmethod
    def graphql(cls, query: str, variables: dict[str, Any] | None = None) -> dict[str, Any]:
        resp = requests.post(
            cls.admin_url("graphql.json"),
            headers=cls.headers(),
            json={"query": query, "variables": variables or {}},
            timeout=120,
        )
        resp.raise_for_status()
        payload = resp.json()
        if payload.get("errors"):
            raise RuntimeError(f"Shopify GraphQL error: {payload['errors']}")
        return payload.get("data") or {}
