"""
Authentication Views
This file contains all the API endpoints for user authentication.
"""

import logging

from rest_framework import status
from rest_framework.decorators import api_view, permission_classes, throttle_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenRefreshView
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.hashers import make_password
from django.utils import timezone

from .models import EmailVerificationOTP, PasswordResetToken, DeviceToken, ImpersonationSession
from .cookies import set_auth_cookies, clear_auth_cookies, REFRESH_COOKIE_NAME
from .throttles import LoginRateThrottle, PasswordResetRateThrottle
from .serializers import (
    UserSerializer, RegisterSerializer, VerifyOTPSerializer,
    LoginSerializer, GoogleLoginSerializer, AppleLoginSerializer, ForgetPasswordSerializer,
    ChangePasswordSerializer, ResendOTPSerializer
)
from .utils import (
    send_otp_email, send_password_reset_email,
    send_welcome_email, verify_google_token, verify_apple_token
)
from business.models import Business, BusinessMembership, PlatformSettings
from business.serializers import BusinessListSerializer

logger = logging.getLogger(__name__)

User = get_user_model()


def get_user_businesses_and_favorites(user):
    """
    Get every business this user can access in business-app — ones they
    own, plus ones they've been invited to as a manager/staff team member
    — and their favorite businesses (for user-app).
    Returns a dict with 'my_businesses' and 'favorite_businesses' lists.
    Each business in 'my_businesses' carries a `my_role` field
    ('owner' | 'manager' | 'staff') so business-app can scope its nav to
    what that role can actually do.
    """
    owned_ids = set(user.businesses.filter(is_active=True).values_list('id', flat=True))
    membership_roles = {
        m.business_id: m.role
        for m in BusinessMembership.objects.filter(user=user, status='active').exclude(role='owner')
    }
    my_businesses_qs = Business.objects.filter(
        id__in=owned_ids | set(membership_roles.keys()), is_active=True
    ).order_by('-created_at')

    my_businesses_data = BusinessListSerializer(my_businesses_qs, many=True).data
    for b in my_businesses_data:
        b['my_role'] = 'owner' if b['id'] in owned_ids else membership_roles.get(b['id'], 'manager')

    # Get favorite businesses
    favorite_businesses = user.favorite_businesses.filter(is_active=True).order_by('-created_at')

    return {
        'my_businesses': my_businesses_data,
        'favorite_businesses': BusinessListSerializer(favorite_businesses, many=True).data,
    }


def get_tokens_for_user(user):
    """
    Generate JWT tokens for a user.
    Returns access and refresh tokens.
    """
    refresh = RefreshToken.for_user(user)
    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }


@api_view(['POST'])
@permission_classes([AllowAny])
def register_user(request):
    """
    Step 1 of Registration: Validate user data and send OTP to email.

    POST /api/auth/register/
    Body:
    {
        "email": "user@example.com",
        "password": "SecurePass123",
        "confirm_password": "SecurePass123",
        "first_name": "John",
        "last_name": "Doe",  (optional)
        "phone_number": "+1234567890"  (optional)
    }
    """
    if not PlatformSettings.load().allow_new_signups:
        return Response(
            {'error': 'New registrations are temporarily disabled. Please check back shortly.'},
            status=status.HTTP_403_FORBIDDEN,
        )

    serializer = RegisterSerializer(data=request.data)

    if serializer.is_valid():
        email = serializer.validated_data['email']
        password = serializer.validated_data['password']
        first_name = serializer.validated_data['first_name']
        last_name = serializer.validated_data.get('last_name', '')
        phone_number = serializer.validated_data.get('phone_number', '')

        # Generate OTP
        otp = EmailVerificationOTP.generate_otp()

        # Hash the password before storing
        password_hash = make_password(password)

        # Delete any existing unverified OTPs for this email
        EmailVerificationOTP.objects.filter(email=email, is_verified=False).delete()

        # Create OTP record with user data
        EmailVerificationOTP.objects.create(
            email=email,
            otp=otp,
            first_name=first_name,
            last_name=last_name,
            phone_number=phone_number,
            password_hash=password_hash
        )

        # Send OTP email (dispatched off the request thread — see
        # authentication/utils.py's _dispatch_email — so this doesn't block on SMTP)
        send_otp_email(email, otp, first_name)

        return Response({
            'message': 'OTP sent to your email. Please verify to complete registration.',
            'email': email
        }, status=status.HTTP_200_OK)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([AllowAny])
def verify_otp(request):
    """
    Step 2 of Registration: Verify OTP and create user account.

    POST /api/auth/verify-otp/
    Body:
    {
        "email": "user@example.com",
        "otp": "123456"
    }
    """
    serializer = VerifyOTPSerializer(data=request.data)

    if serializer.is_valid():
        otp_record = serializer.validated_data['otp_record']

        # Create the user
        user = User.objects.create(
            email=otp_record.email,
            first_name=otp_record.first_name,
            last_name=otp_record.last_name,
            phone_number=otp_record.phone_number,
            password=otp_record.password_hash,  # Already hashed
            is_email_verified=True
        )

        # Mark OTP as verified
        otp_record.is_verified = True
        otp_record.save()

        # Send welcome email
        send_welcome_email(user.email, user.first_name)

        # Generate tokens
        tokens = get_tokens_for_user(user)

        # Get user's businesses and favorites (will be empty for new user)
        business_data = get_user_businesses_and_favorites(user)

        response = Response({
            'message': 'Registration successful!',
            'user': UserSerializer(user).data,
            'tokens': tokens,
            'my_businesses': business_data['my_businesses'],
            'favorite_businesses': business_data['favorite_businesses'],
        }, status=status.HTTP_201_CREATED)
        set_auth_cookies(response, tokens['access'], tokens['refresh'])
        return response

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([AllowAny])
def resend_otp(request):
    """
    Resend OTP for email verification.

    POST /api/auth/resend-otp/
    Body:
    {
        "email": "user@example.com"
    }
    """
    serializer = ResendOTPSerializer(data=request.data)

    if serializer.is_valid():
        email = serializer.validated_data['email']

        # Check if there's a pending OTP for this email
        try:
            otp_record = EmailVerificationOTP.objects.filter(
                email=email,
                is_verified=False
            ).latest('created_at')

            # Generate new OTP and reset the expiry window. Without bumping
            # created_at the resent code would still expire relative to the
            # original timestamp — so a code resent after the original 10
            # minutes would be born already-expired.
            new_otp = EmailVerificationOTP.generate_otp()
            otp_record.otp = new_otp
            otp_record.created_at = timezone.now()
            otp_record.save(update_fields=['otp', 'created_at'])

            # Send new OTP email (dispatched off the request thread)
            send_otp_email(email, new_otp, otp_record.first_name)

            return Response({
                'message': 'New OTP sent to your email.'
            }, status=status.HTTP_200_OK)

        except EmailVerificationOTP.DoesNotExist:
            return Response({
                'error': 'No pending registration found for this email.'
            }, status=status.HTTP_404_NOT_FOUND)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([AllowAny])
@throttle_classes([LoginRateThrottle])
def login_user(request):
    """
    Login with email and password.

    POST /api/auth/login/
    Body:
    {
        "email": "user@example.com",
        "password": "SecurePass123"
    }
    """
    serializer = LoginSerializer(data=request.data)

    if serializer.is_valid():
        email = serializer.validated_data['email']
        password = serializer.validated_data['password']

        # Authenticate user
        user = authenticate(request, username=email, password=password)

        if user is not None:
            if not user.is_active:
                return Response({
                    'error': 'This account has been deactivated.'
                }, status=status.HTTP_403_FORBIDDEN)

            if not user.is_email_verified:
                return Response({
                    'error': 'Please verify your email before logging in.'
                }, status=status.HTTP_403_FORBIDDEN)

            # Generate tokens
            tokens = get_tokens_for_user(user)

            # Get user's businesses and favorites
            business_data = get_user_businesses_and_favorites(user)

            response = Response({
                'message': 'Login successful!',
                'user': UserSerializer(user).data,
                'tokens': tokens,
                'my_businesses': business_data['my_businesses'],
                'favorite_businesses': business_data['favorite_businesses'],
            }, status=status.HTTP_200_OK)
            set_auth_cookies(response, tokens['access'], tokens['refresh'])
            return response
        else:
            return Response({
                'error': 'Invalid email or password.'
            }, status=status.HTTP_401_UNAUTHORIZED)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([AllowAny])
def impersonate_exchange(request):
    """
    POST /api/auth/impersonate/exchange/
    Body: { "code": "..." }
    Trades a one-time impersonation code (issued by admin_impersonate_user
    in business/views_admin.py) for real tokens as the target user.
    Single-use and 60-second-lived so a code that leaks into browser
    history or a server log can't be replayed. AllowAny is correct here,
    same reasoning as the Flutterwave webhook — authenticity comes from
    possessing the one-time code, not a JWT (there isn't one yet).
    """
    code = request.data.get('code')
    if not code:
        return Response({'error': 'Missing code.'}, status=status.HTTP_400_BAD_REQUEST)

    try:
        session = ImpersonationSession.objects.select_related('target_user', 'admin').get(code=code)
    except ImpersonationSession.DoesNotExist:
        return Response({'error': 'Invalid or expired impersonation link.'}, status=status.HTTP_400_BAD_REQUEST)

    if session.exchanged_at:
        return Response({'error': 'This impersonation link has already been used.'}, status=status.HTTP_400_BAD_REQUEST)
    if session.is_expired():
        return Response({'error': 'This impersonation link has expired.'}, status=status.HTTP_400_BAD_REQUEST)

    session.exchanged_at = timezone.now()
    session.save(update_fields=['exchanged_at'])

    target = session.target_user
    tokens = get_tokens_for_user(target)
    business_data = get_user_businesses_and_favorites(target)

    response = Response({
        'message': 'Impersonation session started.',
        'user': UserSerializer(target).data,
        'tokens': tokens,
        'my_businesses': business_data['my_businesses'],
        'favorite_businesses': business_data['favorite_businesses'],
        'impersonation': {
            'session_id': session.id,
            'admin_email': session.admin.email,
            'started_at': session.created_at.isoformat(),
        },
    }, status=status.HTTP_200_OK)
    set_auth_cookies(response, tokens['access'], tokens['refresh'])
    return response


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def impersonate_end(request):
    """
    POST /api/auth/impersonate/end/
    Body: { "session_id": 123 }
    Marks an impersonation session as explicitly ended and writes the
    matching audit-log entry (actor is the admin who started it, not the
    impersonated user making this request) — best-effort, since a closed
    tab won't call this, but covers the normal "Exit impersonation" click.
    Only the impersonated user's own session can end their own record.
    """
    from business.models import AuditLog

    session_id = request.data.get('session_id')
    try:
        session = ImpersonationSession.objects.select_related('admin', 'target_user').get(
            id=session_id, target_user=request.user
        )
    except ImpersonationSession.DoesNotExist:
        return Response({'error': 'Session not found.'}, status=status.HTTP_404_NOT_FOUND)

    session.ended_at = timezone.now()
    session.save(update_fields=['ended_at'])

    AuditLog.objects.create(
        actor=session.admin, action='user.impersonate_end',
        target_type='user', target_id=str(session.target_user_id), target_repr=str(session.target_user),
    )
    return Response({'ok': True}, status=status.HTTP_200_OK)


class CookieTokenRefreshView(TokenRefreshView):
    """
    POST /api/auth/token/refresh/
    Same endpoint as simplejwt's stock view, but also accepts the refresh
    token from the httpOnly cookie — web SPAs never see the raw refresh
    token value to put in a request body — and re-sets both cookies from
    the (rotated, since ROTATE_REFRESH_TOKENS=True) tokens in the response
    so the browser's cookie jar stays in sync. Mobile clients that still
    send `{"refresh": "..."}` in the body work exactly as before.
    """

    def post(self, request, *args, **kwargs):
        data = request.data.copy() if hasattr(request.data, 'copy') else dict(request.data)
        if not data.get('refresh'):
            cookie_refresh = request.COOKIES.get(REFRESH_COOKIE_NAME)
            if cookie_refresh:
                data['refresh'] = cookie_refresh

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)

        response = Response(serializer.validated_data, status=status.HTTP_200_OK)
        set_auth_cookies(response, serializer.validated_data['access'], serializer.validated_data.get('refresh'))
        return response


@api_view(['POST'])
@permission_classes([AllowAny])
def google_login(request):
    """
    Login or Register with Google OAuth.

    POST /api/auth/google-login/
    Body:
    {
        "id_token": "google_id_token_here"
    }
    """
    serializer = GoogleLoginSerializer(data=request.data)

    if serializer.is_valid():
        id_token_string = serializer.validated_data['id_token']

        # Verify Google token
        google_user_info = verify_google_token(id_token_string)

        if not google_user_info:
            logger.error(
                "google_login: token verification failed — check server logs for tokeninfo/google-auth errors. "
                "Token aud prefix: %s",
                id_token_string[:20] if id_token_string else "empty",
            )
            return Response({
                'error': 'Invalid Google token.'
            }, status=status.HTTP_401_UNAUTHORIZED)

        email = google_user_info['email']

        # Check if user exists
        try:
            user = User.objects.get(email=email)

            # Reactivate user if previously deactivated (e.g. after account deletion)
            needs_save = False
            if not user.is_active:
                user.is_active = True
                needs_save = True

            # Update Google user info if not set
            if not user.is_google_user:
                user.is_google_user = True
                user.google_id = google_user_info['google_id']
                user.is_email_verified = True
                needs_save = True

            if needs_save:
                user.save()

        except User.DoesNotExist:
            # Create new user
            user = User.objects.create(
                email=email,
                first_name=google_user_info['first_name'],
                last_name=google_user_info['last_name'],
                is_google_user=True,
                google_id=google_user_info['google_id'],
                is_email_verified=True
            )

            # Send welcome email
            send_welcome_email(user.email, user.first_name)

        # Generate tokens
        tokens = get_tokens_for_user(user)

        # Get user's businesses and favorites
        business_data = get_user_businesses_and_favorites(user)

        response = Response({
            'message': 'Google login successful!',
            'user': UserSerializer(user).data,
            'tokens': tokens,
            'my_businesses': business_data['my_businesses'],
            'favorite_businesses': business_data['favorite_businesses'],
        }, status=status.HTTP_200_OK)
        set_auth_cookies(response, tokens['access'], tokens['refresh'])
        return response

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([AllowAny])
def apple_login(request):
    """
    Login or Register with Sign in with Apple.

    POST /api/auth/apple-login/
    Body:
    {
        "identity_token": "apple_identity_token_here",
        "first_name": "John",  (optional — only sent by the client on first authorization)
        "last_name": "Doe"     (optional — only sent by the client on first authorization)
    }
    """
    serializer = AppleLoginSerializer(data=request.data)

    if serializer.is_valid():
        identity_token = serializer.validated_data['identity_token']

        # Verify Apple token
        apple_user_info = verify_apple_token(identity_token)

        if not apple_user_info or not apple_user_info.get('email'):
            logger.error(
                "apple_login: token verification failed or email missing — check server logs. "
                "Token prefix: %s",
                identity_token[:20] if identity_token else "empty",
            )
            return Response({
                'error': 'Invalid Apple token.'
            }, status=status.HTTP_401_UNAUTHORIZED)

        email = apple_user_info['email']
        first_name = serializer.validated_data.get('first_name') or ''
        last_name = serializer.validated_data.get('last_name') or ''

        # Check if user exists
        try:
            user = User.objects.get(email=email)

            # Reactivate user if previously deactivated (e.g. after account deletion)
            needs_save = False
            if not user.is_active:
                user.is_active = True
                needs_save = True

            # Update Apple user info if not set
            if not user.is_apple_user:
                user.is_apple_user = True
                user.apple_id = apple_user_info['apple_id']
                user.is_email_verified = True
                needs_save = True

            if needs_save:
                user.save()

        except User.DoesNotExist:
            # Create new user. Apple only supplies a name on the user's very
            # first authorization, so fall back to a generic name if missing.
            user = User.objects.create(
                email=email,
                first_name=first_name or 'Apple',
                last_name=last_name,
                is_apple_user=True,
                apple_id=apple_user_info['apple_id'],
                is_email_verified=True
            )

            # Send welcome email
            send_welcome_email(user.email, user.first_name)

        # Generate tokens
        tokens = get_tokens_for_user(user)

        # Get user's businesses and favorites
        business_data = get_user_businesses_and_favorites(user)

        response = Response({
            'message': 'Apple login successful!',
            'user': UserSerializer(user).data,
            'tokens': tokens,
            'my_businesses': business_data['my_businesses'],
            'favorite_businesses': business_data['favorite_businesses'],
        }, status=status.HTTP_200_OK)
        set_auth_cookies(response, tokens['access'], tokens['refresh'])
        return response

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([AllowAny])
@throttle_classes([PasswordResetRateThrottle])
def forget_password(request):
    """
    Request password reset. Sends temporary password to email.

    POST /api/auth/forget-password/
    Body:
    {
        "email": "user@example.com"
    }
    """
    serializer = ForgetPasswordSerializer(data=request.data)

    if serializer.is_valid():
        email = serializer.validated_data['email']

        try:
            user = User.objects.get(email=email)

            # Check if user is a social-login user with no password to reset
            if (user.is_google_user or user.is_apple_user) and not user.password:
                provider = 'Google' if user.is_google_user else 'Apple'
                return Response({
                    'error': f'This account uses {provider} Sign-In. Please login with {provider}.'
                }, status=status.HTTP_400_BAD_REQUEST)

            # Rate limiting: prevent email spamming (60-second cooldown)
            recent_token = PasswordResetToken.objects.filter(
                user=user, is_used=False
            ).first()  # already ordered by -created_at
            if recent_token:
                from datetime import timedelta
                elapsed = (timezone.now() - recent_token.created_at).total_seconds()
                cooldown = 60
                if elapsed < cooldown:
                    remaining = int(cooldown - elapsed)
                    return Response({
                        'error': f'Please wait {remaining} seconds before requesting another password reset.',
                        'retry_after': remaining,
                    }, status=status.HTTP_429_TOO_MANY_REQUESTS)

            # Generate temporary password
            temp_password = PasswordResetToken.generate_temp_password()

            # Delete any existing unused tokens for this user
            PasswordResetToken.objects.filter(user=user, is_used=False).delete()

            # Create password reset token
            PasswordResetToken.objects.create(
                user=user,
                temp_password=temp_password
            )

            # Update user's password
            user.set_password(temp_password)
            user.save()

            # Send email with temporary password (dispatched off the request thread)
            send_password_reset_email(email, temp_password, user.first_name)

            return Response({
                'message': 'A temporary password has been sent to your email.'
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            # Don't reveal if email exists or not (security best practice)
            return Response({
                'message': 'If this email is registered, you will receive a password reset email.'
            }, status=status.HTTP_200_OK)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def change_password(request):
    """
    Change password for logged-in user.

    POST /api/auth/change-password/
    Headers:
    {
        "Authorization": "Bearer access_token"
    }
    Body:
    {
        "old_password": "OldPass123",
        "new_password": "NewPass123",
        "confirm_password": "NewPass123"
    }
    """
    serializer = ChangePasswordSerializer(data=request.data)

    if serializer.is_valid():
        user = request.user

        # Check old password
        if not user.check_password(serializer.validated_data['old_password']):
            return Response({
                'error': 'Old password is incorrect.'
            }, status=status.HTTP_400_BAD_REQUEST)

        # Set new password
        user.set_password(serializer.validated_data['new_password'])
        user.save()

        return Response({
            'message': 'Password changed successfully.'
        }, status=status.HTTP_200_OK)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PATCH', 'PUT'])
@permission_classes([IsAuthenticated])
def get_user_profile(request):
    """
    Get or update current user's profile.

    GET /api/auth/profile/
    PATCH/PUT /api/auth/profile/
    Headers:
    {
        "Authorization": "Bearer access_token"
    }
    Body (for PATCH/PUT):
    {
        "first_name": "John",
        "last_name": "Doe",
        "phone_number": "+1234567890",
        "bio": "About me...",
        "profile_picture": <image_file>
    }
    """
    user = request.user

    if request.method == 'GET':
        return Response({
            'user': UserSerializer(user).data
        }, status=status.HTTP_200_OK)

    # PATCH/PUT - Update profile
    # Handle profile picture upload
    if 'profile_picture' in request.FILES:
        user.profile_picture = request.FILES['profile_picture']

    # Update other fields
    if 'first_name' in request.data:
        user.first_name = request.data['first_name']
    if 'last_name' in request.data:
        user.last_name = request.data['last_name']
    if 'phone_number' in request.data:
        user.phone_number = request.data['phone_number']
    if 'bio' in request.data:
        user.bio = request.data['bio']

    user.save()

    return Response({
        'message': 'Profile updated successfully',
        'user': UserSerializer(user).data
    }, status=status.HTTP_200_OK)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def logout_user(request):
    """
    Logout user. Clears the httpOnly auth cookies (web clients can't delete
    an httpOnly cookie themselves — that's the whole point of httpOnly, so
    the server has to). Mobile clients that authenticate via Bearer header
    just discard their own copy of the tokens client-side, same as before.

    POST /api/auth/logout/
    Headers:
    {
        "Authorization": "Bearer access_token"
    }
    """
    response = Response({
        'message': 'Logout successful.'
    }, status=status.HTTP_200_OK)
    clear_auth_cookies(response)
    return response


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def register_device(request):
    """
    Register FCM device token for push notifications.

    POST /api/auth/register-device/
    Headers:
    {
        "Authorization": "Bearer access_token"
    }
    Body:
    {
        "token": "fcm_device_token_here",
        "device_type": "android",  // android, ios, or web
        "device_name": "Samsung Galaxy S21"  // optional
    }
    """
    token = request.data.get('token')
    device_type = request.data.get('device_type', 'android')
    device_name = request.data.get('device_name', '')

    if not token:
        return Response({
            'error': 'Device token is required.'
        }, status=status.HTTP_400_BAD_REQUEST)

    if device_type not in ['android', 'ios', 'web']:
        return Response({
            'error': 'Invalid device type. Must be android, ios, or web.'
        }, status=status.HTTP_400_BAD_REQUEST)

    # Check if token already exists
    existing_token = DeviceToken.objects.filter(token=token).first()

    if existing_token:
        # Update existing token to current user if different
        if existing_token.user != request.user:
            existing_token.user = request.user
        existing_token.device_type = device_type
        existing_token.device_name = device_name
        existing_token.is_active = True
        existing_token.save()
    else:
        # Create new token
        DeviceToken.objects.create(
            user=request.user,
            token=token,
            device_type=device_type,
            device_name=device_name
        )

    return Response({
        'message': 'Device registered successfully for push notifications.'
    }, status=status.HTTP_200_OK)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def unregister_device(request):
    """
    Unregister FCM device token (e.g., on logout).

    POST /api/auth/unregister-device/
    Headers:
    {
        "Authorization": "Bearer access_token"
    }
    Body:
    {
        "token": "fcm_device_token_here"
    }
    """
    token = request.data.get('token')

    if not token:
        return Response({
            'error': 'Device token is required.'
        }, status=status.HTTP_400_BAD_REQUEST)

    # Deactivate the token
    DeviceToken.objects.filter(
        user=request.user,
        token=token
    ).update(is_active=False)

    return Response({
        'message': 'Device unregistered successfully.'
    }, status=status.HTTP_200_OK)


@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def delete_account(request):
    """
    Delete user account permanently.

    DELETE /api/auth/delete-account/
    Headers:
    {
        "Authorization": "Bearer access_token"
    }
    Body (optional):
    {
        "password": "user_password"  // Required for non-social accounts
    }
    """
    user = request.user
    password = request.data.get('password')

    # For non-social login users, verify password
    if not user.is_google_user and not user.is_apple_user:
        if not password:
            return Response({
                'error': 'Password is required to delete your account.'
            }, status=status.HTTP_400_BAD_REQUEST)

        if not user.check_password(password):
            return Response({
                'error': 'Incorrect password.'
            }, status=status.HTTP_400_BAD_REQUEST)

    # Deactivate all device tokens
    DeviceToken.objects.filter(user=user).update(is_active=False)

    # Soft delete: deactivate the user instead of permanent deletion
    # This preserves data integrity for related records (reviews, businesses, etc.)
    user.is_active = False
    user.save()

    # Alternatively, for hard delete (uncomment if needed):
    # user.delete()

    return Response({
        'message': 'Your account has been deleted successfully.'
    }, status=status.HTTP_200_OK)
