from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from osinacore.models import *
from .serializers import *
from django.contrib.auth import authenticate, login
from django.http import JsonResponse
from django.contrib.auth import AuthenticationFailed


@api_view(['POST'])
def register_customer(request):
    if 'user' in request.data and 'customer' in request.data:
        user_serializer = UserSerializer(data=request.data['user'])
        if user_serializer.is_valid():
            user = user_serializer.save()
            customer_data = request.data['customer']
            customer_serializer = CustomerProfileSerializer(data=customer_data)
            if customer_serializer.is_valid():
                customer_instance = customer_serializer.save(user=user) 
                return Response({'message': 'User and Customer registered successfully'}, status=status.HTTP_201_CREATED)
            else:
                return Response(customer_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response({'message': 'User and Customer data are required'}, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
def authenticate_customer(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        password = request.POST.get('password')
        try:
            user = authenticate(request, username=email, password=password)
            if user is not None:
                login(request, user)
                return JsonResponse({'success': True})
            else:
                return JsonResponse({'success': False, 'error': 'Invalid credentials'})
        except AuthenticationFailed as e:
            # Return the error message provided by the authentication system
            return JsonResponse({'success': False, 'error': str(e)})