import requests
from requests_oauthlib import OAuth2Session

from configs.firebase import SERVER_TIMESTAMP
from functions.Applications import getAppCredentials
from functions.Response import API_Error
from functions.Shops import saveShop


def authUrl(params:dict):
    currentUser =params.get('currentUser')
    uid, enterpriseId, hostname = currentUser.get('uid'), currentUser.get('enterpriseId'), params.get('hostname')
    app = getAppCredentials("8"+enterpriseId)
    if app:
        clientId = app.get('apiKey')
        redirectUri = f"https://{hostname}/shops/redirects/bigcartel"
        print(redirectUri)
        oauth = OAuth2Session(clientId, redirect_uri=redirectUri)
        authorization_url, state = oauth.authorization_url('https://my.bigcartel.com/oauth/authorize')
        return dict(state = state, url = authorization_url)
    raise API_Error(message="No app credentials found", status_code=500)

def authToken(params:dict):
    currentUser = params.get('currentUser')
    uid, enterpriseId, hostname = currentUser.get('uid'), currentUser.get('enterpriseId'), params.get('hostname')
    app = getAppCredentials(platformId="8", enterpriseId=enterpriseId)
    if app:
        clientId = app.get('apiKey')
        clientSecret = app.get('apiSecret')
        url = "https://api.bigcartel.com/oauth/token"
        token = requests.post(url, data=dict(client_id = clientId, client_secret = clientSecret, code = params.get('code')))
        if token.status_code not in [200, 201]:
            raise API_Error(message=token.text, status_code=token.status_code)
        data = token.json()
        accountId = data.get('account_id')
        accountRes = requests.get(f"https://api.bigcartel.com/v1/accounts/{accountId}.json", headers=getAuth(data.get('access_token')))
        if accountRes.status_code in [200,201]:
            account = accountRes.json().get('data', {}).get("attributes")
            shop = saveShop(
                uid=uid,
                enterpriseId=enterpriseId,
                platformId="8",
                platformName="Bigcartel",
                appId=app.get('id'),
                name=account.get('store_name'),
                platformShopId = accountId,
                accessToken = data.get('access_token'),
                accountId = accountId,
                createdAt=SERVER_TIMESTAMP,
                updatedAt=SERVER_TIMESTAMP,
                url  = account.get('url'),
        )
            return shop
        raise API_Error(accountRes.text, status_code=accountRes.status_code)
    raise API_Error(message="No app credentials found", status_code=500)

def getAuth(access_token:str):
    return {
        "Authorization": f"Bearer {access_token}",
        "Accept": "application/vnd.api+json",
        "Content-Type": "application/vnd.api+json"
    }