import secrets
import string
from datetime import datetime, timedelta
import requests
import json


class BigCommerceService:
    @staticmethod
    def generate_random_code(size=6, chars=string.ascii_letters + string.digits):
        return "".join(secrets.choice(chars) for _ in range(size))

    @staticmethod
    def create_single_use_discount_code(
        store_path,
        auth_token,
        auth_client,
        offer_name,
        percent_or_cash_off,
        compensation,
        min_purchase_amount=0,
        expiration_days=30,
    ):
        url = f"https://api.bigcommerce.com/stores/{store_path}/v2/coupons"
        headers = {
            "X-Auth-Token": auth_token,
            "X-Auth-Client": auth_client,
            "Content-Type": "application/json",
        }

        # Calculate expiration date to be one month from now
        expiration_date = datetime.now() + timedelta(days=expiration_days)
        formatted_expiration_date = expiration_date.strftime(
            "%a, %d %b %Y %H:%M:%S +0000"
        )

        # Generate a random coupon code
        coupon_code = BigCommerceService.generate_random_code()

        # Use the current timestamp to ensure the name is unique
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        coupon_name = f"StoryIt: {offer_name} - {timestamp} (Do not edit)"

        # Coupon details
        data = {
            "name": coupon_name,
            "type": (
                "per_total_discount"
                if percent_or_cash_off == "Cash"
                else "percentage_discount"
            ),
            "amount": compensation,
            "min_purchase": min_purchase_amount,
            "expires": formatted_expiration_date,
            "enabled": True,
            "code": coupon_code,  # Use the generated random code
            "applies_to": {"entity": "categories", "ids": [0]},
            "max_uses": 1,
        }

        # Sending the POST request
        response = requests.post(url, headers=headers, json=data)

        # Handling the response
        print("Status Code:", response.status_code)
        if response.status_code == 409:
            print("Conflict detected: A coupon with this code may already exist.")
        elif response.content:
            try:
                response_data = response.json()
                print("Response Body:", response_data)
            except json.JSONDecodeError:
                print("Failed to decode JSON, raw response text:", response.text)
        else:
            print("No response body was received.")

        # Output the generated coupon code for reference
        print("Generated Coupon Code:", coupon_code)
        return coupon_code
