import json
import requests
import aiohttp

async def get_all_rules(shop_name, apikey_bss):
    print(shop_name)
    print(apikey_bss)

    data = {
        "domain": 'emde-b2b.myshopify.com',
        "accessKey": 'c4uiY9TEKt07cK0LuRkruq7eRX0+Xo6vIigtHzpEueg=',
    }
    url = "https://b2b-solution-public-api.bsscommerce.com/api/v1/rule/get-by-domain"
    headers = {
        "Content-Type": "application/json",
    }

    try:
        response = requests.post(url, headers=headers, json=data)
    except requests.RequestException as e:
        raise Exception(f"Request error: {e}")

    try:
        response_decoded = response.json()
    except json.JSONDecodeError as e:
        raise Exception(f"Erreur de décodage JSON: {e}")

    return response_decoded

async def create_or_update_rule_async(priority, product_condition_type, apply_to, name, customer_tag, product_tag,
                                       customer_id, price, rule_id, api_key_bss, variant_id, discount_type=2, product_id=None):
    base_rule = {
        "name": name,
        "priority": priority,
        "status": 1,
        "apply_to": apply_to,
        "product_condition_type": product_condition_type,
        "customer_ids": [customer_id],
        "customer_tags": [customer_tag],
        "product_ids": [product_id],
        "variant_ids": [variant_id],
        "product_collections": [],
        "product_tags": [product_tag],
        "exclude_from": 0,
        "exc_customers": [],
        "exc_customer_tags": [],
        "market_condition_type": 0,
        "market_ids": [],
        "discount_type": discount_type,
        "discount_value": price,
        "start_date": None,
        "end_date": None
    }

    if rule_id is not None:
        base_rule["id"] = rule_id

    data = {
        "domain": 'emde-b2b.myshopify.com',
        "accessKey": api_key_bss,
        "rule": base_rule
    }

    url = "https://b2b-solution-public-api.bsscommerce.com/api/v1/rule/save"
    headers = {
        "Content-Type": "application/json",
        "Connection": "close",
        "Accept-Encoding": "identity",
    }

    async with aiohttp.ClientSession() as session:
        async with session.post(url, headers=headers, json=data) as response:
            result = await response.json()
            print(result)
            if response.status != 200:
                print("Erreur HTTP:", response.status)
                print("Response:", await response.text())

