from django.shortcuts import render
from rest_framework.permissions import AllowAny
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import CustomerRegisterSerializer

class CustomerRegisterView(APIView):
    permission_classes = [AllowAny]  # Allow public access

    def post(self, request):
        serializer = CustomerRegisterSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({"message": "Customer registered successfully"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from orders.permissions import IsAdmin,IsManager,IsAdminOrManager
from django.contrib.auth import get_user_model

User = get_user_model()


class ApproveUserView(APIView):
    permission_classes = [IsAuthenticated, IsAdminOrManager]

    def patch(self, request, pk):
        try:
            user = User.objects.get(pk=pk, is_approved=False)
        except User.DoesNotExist:
            return Response({"error": "User not found"}, status=404)

        user.is_approved = True
        user.is_active = True
        user.save()

        return Response({"message": "User approved successfully"})
from django.conf import settings
from .models import PasswordResetOTP
from .utils import generate_otp
import logging
from django.core.mail import send_mail
from rest_framework import status
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
logger = logging.getLogger(__name__)
User = get_user_model()


class ForgotPasswordAPIView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.data.get("email")
        if not email:
            return Response({"error": "Email required"}, status=status.HTTP_400_BAD_REQUEST)

        # Avoid MultipleObjectsReturned by picking a single user (prefer active)
        user = User.objects.filter(email__iexact=email, is_active=True).order_by("id").first()
        if not user:
            user = User.objects.filter(email__iexact=email).order_by("id").first()
        if not user:
            # Keep response generic for security
            return Response({"message": "If an account with that email exists, a reset code has been sent."}, status=status.HTTP_200_OK)

        try:
            otp = generate_otp()
            PasswordResetOTP.objects.create(user=user, otp=otp)
        except Exception as e:
            logger.exception("Failed creating OTP object")
            return Response({"error": "Server error creating OTP"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        from_email = getattr(settings, "DEFAULT_FROM_EMAIL", "no-reply@localhost")

        try:
            send_mail(
                subject="Password Reset OTP",
                message=f"Your OTP is {otp}. It expires in 2 minutes.",
                from_email=from_email,
                recipient_list=[user.email],
                fail_silently=False,
            )
        except Exception as e:
            logger.exception("Failed sending password reset email")
            # Clean up OTP if email failed
            try:
                PasswordResetOTP.objects.filter(user=user, otp=otp).delete()
            except Exception:
                pass
            return Response({"error": "Failed to send email"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # DEBUG convenience: return otp in response only when DEBUG True
        if getattr(settings, "DEBUG", False):
            return Response({"message": "OTP sent to email ."}, status=status.HTTP_200_OK)

        return Response({"message": "If an account with that email exists, a reset code has been sent."}, status=status.HTTP_200_OK)


class ResetPasswordAPIView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.data.get("email")
        otp = request.data.get("otp")
        new_password = request.data.get("new_password")

        if not all([email, otp, new_password]):
            return Response({"error": "All fields required"}, status=status.HTTP_400_BAD_REQUEST)

        # Select a user safely (prefer active)
        user = User.objects.filter(email__iexact=email, is_active=True).order_by("-id").first()
        if not user:
            user = User.objects.filter(email__iexact=email).order_by("-id").first()
        if not user:
            return Response({"error": "Invalid OTP or user"}, status=status.HTTP_400_BAD_REQUEST)

        otp_obj = PasswordResetOTP.objects.filter(user=user, otp=otp).order_by("-created_at").first()
        if not otp_obj:
            return Response({"error": "Invalid OTP"}, status=status.HTTP_400_BAD_REQUEST)

        if otp_obj.is_expired():
            otp_obj.delete()
            return Response({"error": "OTP expired"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            user.password = make_password(new_password)
            user.save()
            otp_obj.delete()
        except Exception as e:
            logger.exception("Failed to reset password")
            return Response({"error": "Server error"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response({"message": "Password reset successful"}, status=status.HTTP_200_OK)
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError

class ChangePasswordView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user

        old_password = request.data.get("old_password")
        new_password = request.data.get("new_password")

        if not user.check_password(old_password):
            return Response(
                {"error": "Old password is incorrect"},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            validate_password(new_password, user)
        except ValidationError as e:
            return Response(
                {"error": e.messages},
                status=status.HTTP_400_BAD_REQUEST
            )

        user.set_password(new_password)
        user.save()

        return Response(
            {"success": "Password updated successfully"},
            status=status.HTTP_200_OK
        )


class DriverListView(APIView):
    permission_classes = [IsAuthenticated, IsAdminOrManager]

    def get(self, request):
        drivers = User.objects.filter(role="DRIVER", is_active=True).order_by("username")
        return Response(
            [
                {"id": driver.id, "username": driver.username, "phone_number": driver.phone_number}
                for driver in drivers
            ]
        )
