"""Setup-wizard endpoints.

`GET /api/setup/status/` reports whether the org has finished initial SaaS
setup (org profile filled, an admin exists, RBAC roles seeded). The frontend
hard-gates the app on this until `setup_complete` is true.

`POST /api/setup/invite/` creates a teammate account with a temporary password
and forces a password change on first login.
"""

from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import User, Role

DEFAULT_ORG_NAME = "My Organization"


def _org_profile_complete(org) -> bool:
    if org is None:
        return False
    named = bool(org.name) and org.name.strip() != DEFAULT_ORG_NAME
    has_contact = bool(org.email or org.phone or org.website)
    return named and has_contact


class SetupStatusView(APIView):
    """Read-only setup completeness. Any authenticated user may read it
    (the frontend only redirects admins to the wizard)."""

    permission_classes = [IsAuthenticated]

    def get(self, request):
        from apps.companies.models import OrgProfile

        org = OrgProfile.objects.first()
        org_complete = _org_profile_complete(org)
        has_admin = User.objects.filter(is_superuser=True).exists()
        roles_seeded = Role.objects.filter(is_system=True).exists()

        return Response({
            "setup_complete": org_complete and has_admin and roles_seeded,
            "org_profile_complete": org_complete,
            "has_admin": has_admin,
            "roles_seeded": roles_seeded,
            "total_users": User.objects.count(),
        })


class SetupInviteView(APIView):
    """Create a teammate account during setup. Admin-only."""

    permission_classes = [IsAdminUser]

    def post(self, request):
        email = (request.data.get("email") or "").strip().lower()
        password = request.data.get("password") or ""
        if not email:
            return Response({"error": "email is required"}, status=400)
        if not password:
            return Response({"error": "password is required"}, status=400)
        if User.objects.filter(email__iexact=email).exists():
            return Response({"error": "a user with this email already exists"}, status=400)

        user = User.objects.create_user(
            email=email,
            password=password,
            first_name=(request.data.get("first_name") or "").strip(),
            last_name=(request.data.get("last_name") or "").strip(),
            must_change_password=True,
        )
        return Response({"id": str(user.id), "email": user.email}, status=201)
