import aiohttp
from flask import current_app


class MultiSaasClient:
    def _get_config(self):
        return {
            "api_url": current_app.config.get("MULTISAAS_API_URL", ""),
            "api_key": current_app.config.get("MULTISAAS_API_KEY", ""),
        }

    async def create_tenant(self, name: str, email: str, subdomain: str) -> dict:
        cfg = self._get_config()
        if not cfg["api_url"]:
            return {"error": "MultiSaas not configured"}
        url = f"{cfg['api_url']}/api/tenants"
        headers = {"Authorization": f"Bearer {cfg['api_key']}", "Content-Type": "application/json"}
        payload = {"name": name, "email": email, "subdomain": subdomain}
        async with aiohttp.ClientSession() as session:
            async with session.post(url, json=payload, headers=headers) as resp:
                return await resp.json()

    async def set_custom_domain(self, tenant_id: str, domain: str) -> dict:
        cfg = self._get_config()
        url = f"{cfg['api_url']}/api/tenants/{tenant_id}/domain"
        headers = {"Authorization": f"Bearer {cfg['api_key']}", "Content-Type": "application/json"}
        async with aiohttp.ClientSession() as session:
            async with session.put(url, json={"domain": domain}, headers=headers) as resp:
                return await resp.json()

    async def get_tenant_status(self, tenant_id: str) -> dict:
        cfg = self._get_config()
        url = f"{cfg['api_url']}/api/tenants/{tenant_id}"
        headers = {"Authorization": f"Bearer {cfg['api_key']}"}
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=headers) as resp:
                return await resp.json()
