import traceback

import requests

from configs.firebase import ArrayRemove, ArrayUnion, db
from functions.Response import API_Error
from functions.Suppliers.Pricing import getBlankVariantPrice
from V2.Params import Params

api_token = "XR7pJeG12SlLSMYGW2SRHvUN"
project_id = "prj_IwBIAM0rRp7aC9AJwAPRlIXpNG4c"


def addPrimaryDomain(params:Params):
    currentUser = params.currentUser
    enterpriseId = currentUser.enterpriseId
    domain = params.args.get("domain")
    enterprise = db.collection("enterprises").document(enterpriseId).get().to_dict()
    existingDomains = enterprise.get("hostnames", [])
    db.collection("enterprises").document(enterpriseId).update({
        "hostnames": [domain]+ [without for without in existingDomains if without != domain],
    })
    return {"status": "success", "primaryDomain": domain, "hostnames": existingDomains}

def addCustomDomain(params:Params):
    currentUser = params.currentUser
    enterpriseId = currentUser.enterpriseId
    domains = params.args.get("domains")
    primaryDomain = params.args.get("primaryDomain")
    query = db.collection("enterprises").where("hostnames", "array_contains_any", domains).get()
    if query: raise API_Error("Domain already exists", 400)
    url = f"https://api.vercel.com/v1/projects/{project_id}/domains"
    headers = {
        "Authorization": f"Bearer {api_token}",
        "Content-Type": "application/json"
    }
    for domain in domains:
        payload = {
            "name": domain,
            "redirect": primaryDomain
            }
        try:
            response = requests.post(url, headers=headers, json=payload)
            response.raise_for_status()  # Raise an error for HTTP status codes >= 400
            if response.status_code in [200, 201]:
                data = response.json()
                if not data.get("verified"): db.collection("enterprises").document(enterpriseId).update({
                        "pendingHostnames": ArrayUnion([domain])
                    })
                else: db.collection("enterprises").document(enterpriseId).update({
                        "hostnames": ArrayUnion([domain])
                    })
                return response.json()
        except requests.exceptions.RequestException as e:
            print(e)
            return None

import requests


def verifyCustomDomain(params: Params):
    """
    Verifies a custom domain in a Vercel project.
    
    :param api_token: str - The Vercel API token.
    :param project_id: str - The Vercel project ID.
    :param domain: str - The custom domain to verify.
    :return: dict - Response from the Vercel API.
    """
    domain = params.args.get("domain")
    url = f"https://api.vercel.com/v1/projects/{project_id}/domains/{domain}/verify"
    headers = {
        "Authorization": f"Bearer {api_token}",
        "Content-Type": "application/json"
    }
    enterpriseId = params.currentUser.enterpriseId
    try:
        response = requests.post(url, headers=headers)
        response.raise_for_status()  # Raise an error for HTTP status codes >= 400
        if response.status_code in [200, 201]:
            if response.json().get("verified"):
                db.document(f"enterprises/{enterpriseId}").update({
                    "hostnames": ArrayRemove([domain]),
                    "pendingHostnames": ArrayUnion([domain])

                })
        return response.json()
    except requests.exceptions.RequestException as e:
        return {"error": str(e), "status_code": response.status_code if 'response' in locals() else None}

def getEnterpriseByHostname(hostname):
    ref = db.collection("enterprises").where("hostnames", "array_contains", hostname).get()
    return ref[0].to_dict()

def getEnterpriseById(enterpriseId):
    ref = db.collection("enterprises").document(enterpriseId).get()
    return ref.to_dict()

def getItemCost(enterpriseId, blankProductId, blankVariantId):
    try: 
        printPrice = 0
        blankVariantPrice  = 0 
        upcharge = 0
        blankSettings= db.collection("enterprises").document(enterpriseId).collection("blankProducts").document(blankProductId).get().to_dict()
        if not blankSettings:
            print("no blank settings", enterpriseId, blankProductId)
        else:
            placements = blankSettings.get("placements", {})
            placement = placements.get("1", placements.get("2", {}))
            printPrice = placement.get("printingPrice", 0)
            upcharge = placement.get("upcharge", 0)
        if not printPrice or type(printPrice) not in [int, float]: printPrice = 0        
        blankVariantPrice = getBlankVariantPrice(blankProductId, blankVariantId, enterpriseId)
        if type(upcharge) not in (int, float): upcharge = 0
        if blankVariantPrice is None: blankVariantPrice = 0
        return round(float(printPrice)+float(blankVariantPrice)+float(blankVariantPrice*upcharge)/100,2)
    except Exception as e: 
        print(traceback.format_exc())
        return 0
