from __future__ import annotations

from typing import Any, Dict, List, Optional

from shopify.connections import build_client

PRODUCT_DELETE_MUTATION = """
mutation productDelete($input: ProductDeleteInput!) {
  productDelete(input: $input) {
    deletedProductId
    userErrors {
      field
      message
    }
  }
}
"""


def delete_product_by_id(client, product_id: str) -> Dict[str, Any]:
    """Delete one Shopify product by Admin API GID."""
    product_id = str(product_id or "").strip()
    if not product_id:
        return {"remote_id": product_id, "status": "failed", "error": "missing product id"}

    data = client.graphql(PRODUCT_DELETE_MUTATION, {"input": {"id": product_id}})
    payload = (data or {}).get("productDelete") or {}
    errors = payload.get("userErrors") or []
    if errors:
        return {
            "remote_id": product_id,
            "status": "failed",
            "error": "; ".join(str(e.get("message") or e) for e in errors),
        }
    deleted_id = payload.get("deletedProductId")
    if not deleted_id:
        return {"remote_id": product_id, "status": "failed", "error": "no deletedProductId returned"}
    return {"remote_id": product_id, "status": "ok", "deleted_product_id": deleted_id}


def delete_products_by_id(connection, product_ids: List[str]) -> List[Dict[str, Any]]:
    """Delete Shopify products by GID using stored connection credentials."""
    client = build_client(connection)
    results: List[Dict[str, Any]] = []
    for product_id in product_ids:
        product_id = str(product_id or "").strip()
        if not product_id:
            continue
        try:
            results.append(delete_product_by_id(client, product_id))
        except Exception as exc:
            results.append({"remote_id": product_id, "status": "failed", "error": str(exc)})
    return results
