import requests
from requests.auth import HTTPBasicAuth

from configs.firebase import SERVER_TIMESTAMP, ArrayUnion, db
from functions.Applications import getAppCredentials
from functions.Response import API_Error
from functions.Shops import saveShop


def saveShipstation(data:dict):
    currentUser = data.get('currentUser')
    uid, enterpriseId = currentUser.get('uid'), currentUser.get('enterpriseId')
    apiKey, apiSecret, name = data.get('apiKey'), data.get('apiSecret'), data.get('name')
    storeIds = data.get("storeIds", [])
    stores = data.get("stores", [])
    shop = saveShop(
        uid=uid,
        platformId="5",
        enterpriseId=enterpriseId,
        platformShopId=f"5-{uid}-{name}",
        platformName= "Shipstation",
        appId= "5"+enterpriseId,
        createdAt= SERVER_TIMESTAMP,
        apiKey=apiKey,
        apiSecret=apiSecret,
        name=name,
        updatedAt=SERVER_TIMESTAMP,
        url=None,
        platformShopIds=storeIds,
        platformShops=stores
    )
    return shop

def Authorization(apiKey, apiSecret):
    return HTTPBasicAuth(apiKey, apiSecret)


def getStores(data:dict):
    apiKey, apiSecret = data.get("apiKey"), data.get("apiSecret")
    url = "https://ssapi.shipstation.com/stores"
    response = requests.request("GET", url, auth=Authorization(apiKey, apiSecret))
    return response.json()