import hmac
import logging

from django.http import JsonResponse
from django.shortcuts import redirect
from django.urls import reverse
from NexusApp.jwt_auth import (
    clear_staff_token_cookie,
    create_staff_token,
    set_staff_token_cookie,
)
from NexusApp.models import Staff
from NexusApp.utils.crypto import decrypt_password
from django.db import transaction
from NexusApp.utils.crypto import decrypt_password, encrypt_password

logger = logging.getLogger(__name__)


def staff_login_validate(request):
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)

    email = request.POST.get('email', '').strip()
    password = request.POST.get('password', '').strip()   # add_staff stores it stripped too

    errors = {}
    if not email:
        errors['email'] = 'Email is required.'
    elif '@' not in email:
        errors['email'] = 'Please enter a valid email address.'
    if not password:
        errors['password'] = 'Password is required.'
    if errors:
        return JsonResponse({'status': 'error', 'errors': errors}, status=400)

    try:
        staff = Staff.objects.filter(email__iexact=email).first()

        # Passwords are Fernet-encrypted (admin can view them), so decrypt and
        # compare in constant time. Same generic message for "no such email"
        # and "wrong password" so the form doesn't reveal which emails exist.
        stored = decrypt_password(staff.password) if staff else ''
        valid = bool(stored) and hmac.compare_digest(stored.encode(), password.encode())
        if not valid:
            logger.warning(f"staff login failed. email: {email}")
            return JsonResponse(
                {'status': 'error', 'message': 'Invalid email or password.'}, status=400)

        if (staff.status or '').lower() != 'active':
            logger.warning(f"staff login blocked - inactive. staff_id: {staff.id}")
            return JsonResponse({
                'status': 'error',
                'message': 'Your account is inactive. Please contact the admin.',
            }, status=403)

        token = create_staff_token(staff)
        logger.info(f"staff login successful. staff_id: {staff.id}, ip: {request.META.get('REMOTE_ADDR')}")

        response = JsonResponse({
            'status': 'success',
            'message': 'Login successful',
            'redirect_url': reverse('staff:dashboard'),
        })
        return set_staff_token_cookie(response, token)

    except Exception:
        logger.exception("staff login failed with exception")
        return JsonResponse(
            {'status': 'error', 'message': 'Something went wrong. Please try again.'}, status=500)

def staff_logout(request):
    staff = getattr(request, 'staff', None)
    logger.info(f"staff logout. staff_id: {staff.id if staff else None}")
    return clear_staff_token_cookie(redirect('staff:staff_login'))

MIN_PASSWORD_LENGTH = 8
def staff_reset_password(request):
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)

    staff = getattr(request, 'staff', None)
    if not staff:
        return JsonResponse({
            'status': 'error',
            'message': 'Session expired. Please log in again.',
            'redirect_url': reverse('staff:staff_login'),
        }, status=401)

    current_password = request.POST.get('current_password', '').strip()
    new_password = request.POST.get('new_password', '').strip()
    confirm_password = request.POST.get('confirm_password', '').strip()

    # ---------- Validation ----------
    errors = {}
    if not current_password:
        errors['current_password'] = 'Current password is required.'

    if not new_password:
        errors['new_password'] = 'New password is required.'
    elif len(new_password) < MIN_PASSWORD_LENGTH:
        errors['new_password'] = f'Password must be at least {MIN_PASSWORD_LENGTH} characters.'
    elif new_password == current_password:
        errors['new_password'] = 'New password must be different from the current password.'

    if not confirm_password:
        errors['confirm_password'] = 'Please confirm your new password.'
    elif new_password and confirm_password != new_password:
        errors['confirm_password'] = 'Passwords do not match.'

    if errors:
        return JsonResponse({'status': 'error', 'errors': errors}, status=400)

    try:
        # ---------- Verify current password (constant-time compare) ----------
        stored = decrypt_password(staff.password) or ''
        if not stored or not hmac.compare_digest(stored.encode(), current_password.encode()):
            logger.warning(f"staff reset password failed - wrong current password. staff_id: {staff.id}")
            return JsonResponse({
                'status': 'error',
                'errors': {'current_password': 'Current password is incorrect.'},
            }, status=400)

        # ---------- Save ----------
        with transaction.atomic():
            staff.password = encrypt_password(new_password)
            staff.save(update_fields=['password'])

        logger.info(f"staff password reset. staff_id: {staff.id}, ip: {request.META.get('REMOTE_ADDR')}")
        return JsonResponse({
            'status': 'success',
            'message': 'Password updated successfully.',
            'redirect_url': reverse('staff:staff_login'),
        })

    except Exception:
        logger.exception("staff reset password failed with exception")
        return JsonResponse(
            {'status': 'error', 'message': 'Something went wrong. Please try again.'}, status=500)