import aiohttp
import asyncio
import json
import hashlib
import base64
from config import HELEKET_MERCHANT, HELEKET_SIGN


def generate_signature(data, api_key):
    json_data = json.dumps(data)
    base64_data = base64.b64encode(json_data.encode('utf-8')).decode('utf-8')
    sign = hashlib.md5((base64_data + api_key).encode('utf-8')).hexdigest()
    return sign


async def create_payment(amount, order_id):
    url = 'https://api.heleket.com/v1/payment'
    amount = str(amount).replace(',', '.')

    data = {
        "amount": amount,
        "currency": 'USD',
        "order_id": order_id
    }
    

    sign = generate_signature(data, HELEKET_SIGN)
    
    headers = {
        'merchant': HELEKET_MERCHANT,
        'sign': sign,
        'Content-Type': 'application/json'
    }

    async with aiohttp.ClientSession() as session:
        async with session.post(url, headers=headers, json=data) as response:
            if response.status == 200:
                payment_response = await response.json()
                return payment_response
            else:
                return {"error": "Failed to create payment", "status": response.status}


async def get_payment_info(uuid=None, order_id=None):
    url = 'https://api.heleket.com/v1/payment/info'
    if not uuid and not order_id:
        return {"error": "Either uuid or order_id is required"}
    
    data = {}
    if uuid:
        data["uuid"] = uuid
    if order_id:
        data["order_id"] = order_id
    
    sign = generate_signature(data, HELEKET_SIGN)
    
    headers = {
        'merchant': HELEKET_MERCHANT,
        'sign': sign,
        'Content-Type': 'application/json'
    }
    
    async with aiohttp.ClientSession() as session:
        async with session.post(url, headers=headers, json=data) as response:
            if response.status == 200:
                payment_info = await response.json()
                return payment_info
            else:
                return {"error": "Failed to get payment info", "status": response.status}