"""
4Alarm - Tenant management routes (super-admin only)
"""
from fastapi import APIRouter, HTTPException, Depends
from datetime import datetime, timezone
import uuid
import bcrypt


def setup_tenant_routes(get_current_user, db):
    router = APIRouter(prefix="/tenants", tags=["tenants"])

    def require_superadmin(user):
        if user.get("rol") != "superadmin":
            raise HTTPException(status_code=403, detail="Solo super-admin")

    @router.get("")
    async def list_tenants(user: dict = Depends(get_current_user)):
        require_superadmin(user)
        tenants = await db.tenants.find({}, {"_id": 0, "tuya_access_secret": 0}).sort("nombre", 1).to_list(200)
        # Add user/device counts
        for t in tenants:
            t["users_count"] = await db.users.count_documents({"tenant_id": t["id"]})
            t["devices_count"] = await db.devices.count_documents({"tenant_id": t["id"]})
        return tenants

    @router.post("")
    async def create_tenant(data: dict, user: dict = Depends(get_current_user)):
        require_superadmin(user)
        nombre = (data.get("nombre") or "").strip()
        slug = (data.get("slug") or "").strip().lower().replace(" ", "-")
        if not nombre or not slug:
            raise HTTPException(status_code=400, detail="Nombre y slug requeridos")
        existing = await db.tenants.find_one({"slug": slug})
        if existing:
            raise HTTPException(status_code=400, detail="Slug ya existe")
        tenant = {
            "id": str(uuid.uuid4()),
            "nombre": nombre,
            "slug": slug,
            "estado": "activo",
            "tuya_access_id": (data.get("tuya_access_id") or "").strip(),
            "tuya_access_secret": (data.get("tuya_access_secret") or "").strip(),
            "tuya_endpoint": data.get("tuya_endpoint", "https://openapi.tuyaus.com"),
            "vapid_public_key": (data.get("vapid_public_key") or "").strip(),
            "vapid_private_key": (data.get("vapid_private_key") or "").strip(),
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
        await db.tenants.insert_one(tenant)
        tenant.pop("_id", None)
        # Create admin user for this tenant
        admin_email = data.get("admin_email", "").strip().lower()
        admin_password = data.get("admin_password", "")
        if admin_email and admin_password:
            existing_u = await db.users.find_one({"email": admin_email})
            if existing_u:
                raise HTTPException(status_code=400, detail="Email admin ya existe")
            pw = bcrypt.hashpw(admin_password.encode(), bcrypt.gensalt()).decode()
            admin_user = {
                "id": str(uuid.uuid4()),
                "email": admin_email,
                "nombre": f"Admin {nombre}",
                "rol": "admin",
                "tenant_id": tenant["id"],
                "password_hash": pw,
                "created_at": datetime.now(timezone.utc).isoformat(),
            }
            await db.users.insert_one(admin_user)
        return tenant

    @router.put("/{tenant_id}")
    async def update_tenant(tenant_id: str, data: dict, user: dict = Depends(get_current_user)):
        require_superadmin(user)
        allowed = ("nombre", "estado", "tuya_access_id", "tuya_access_secret", "tuya_endpoint", "vapid_public_key", "vapid_private_key")
        update = {k: v for k, v in data.items() if k in allowed}
        if not update:
            raise HTTPException(status_code=400, detail="Nada para actualizar")
        result = await db.tenants.update_one({"id": tenant_id}, {"$set": update})
        if result.matched_count == 0:
            raise HTTPException(status_code=404, detail="Tenant no encontrado")
        return await db.tenants.find_one({"id": tenant_id}, {"_id": 0, "tuya_access_secret": 0})

    @router.get("/{tenant_id}")
    async def get_tenant(tenant_id: str, user: dict = Depends(get_current_user)):
        # Admin can see their own tenant, superadmin can see any
        if user.get("rol") == "superadmin" or user.get("tenant_id") == tenant_id:
            tenant = await db.tenants.find_one({"id": tenant_id}, {"_id": 0})
            if not tenant:
                raise HTTPException(status_code=404, detail="Tenant no encontrado")
            # Hide secret for non-superadmin
            if user.get("rol") != "superadmin":
                tenant.pop("tuya_access_secret", None)
                tenant.pop("vapid_private_key", None)
            return tenant
        raise HTTPException(status_code=403, detail="Sin acceso")

    return router
