import secrets
import string
from datetime import datetime

import requests


class EventbriteService:

    @staticmethod
    def generate_random_code(size=6, chars=string.ascii_letters + string.digits):
        return ''.join(secrets.choice(chars) for _ in range(size))
    
    @staticmethod
    def add_one_month(orig_date):
        new_year = orig_date.year + (orig_date.month // 12)
        new_month = orig_date.month % 12 + 1
        new_day = min(orig_date.day, 28)
        return datetime(new_year, new_month, new_day)
    
    @staticmethod
    def create_event_discount_code(organization_id, event_id, access_token, discount_value, discount_type):
        code = EventbriteService.generate_random_code()
        end_date = EventbriteService.add_one_month(datetime.now()).isoformat()
        
        # Determine discount type
        if discount_type == 'cash':
            discount_key = 'amount_off'
        elif discount_type == 'percent':
            discount_key = 'percent_off'
        else:
            raise ValueError("Invalid discount type. Please use 'amount' or 'percent'.")

        discount_data = {
            "discount": {
                "type": "coded",
                "code": code,
                discount_key: discount_value,
                "event_id": event_id,
                "quantity_available": 1,
                "end_date": end_date,
            }
        }
        url = f'https://www.eventbriteapi.com/v3/organizations/{organization_id}/discounts/'
        headers = {
            'Authorization': f'Bearer {access_token}',
            'Content-Type': 'application/json',
        }
        response = requests.post(url, json=discount_data, headers=headers)

        if response.status_code == 200:
            data = response.json()
            print(f"Discount created successfully! Details: {data}")
            return code
        else:
            print(f"Error {response.status_code}: {response.text}")
            return None