from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.response import Response
from authentication.models import City, SystemUserProfile, SystemAddress
from authentication.views import ARTA_URL_REGISTER
from panel.admin import PROJECT_API_KEY
from panel.models import Guilds, Wallet
import requests


def register_user(group, city_name, mobile, first_name, last_name, national_id, postal_code, address_text):
    try:
        # Fetch city and related province
        city = City.objects.select_related('province').get(name=city_name)
        province = city.province
    except City.DoesNotExist:
        return Response({"result": "شهر یافت نشد"}, status=status.HTTP_400_BAD_REQUEST)

    # Check if user profile exists and if they are associated with a guild
    system_profile = SystemUserProfile.objects.filter(mobile=mobile, trash=False).last()
    if system_profile and Guilds.objects.filter(user=system_profile, trash=False).exists():
        return Response({"result": "این صنف قبلا ثبت شده است"}, status=status.HTTP_403_FORBIDDEN)

    # Register a new user if system profile does not exist
    if not system_profile:
        password = "123456"
        registration_data = {
            "username": mobile,
            "password": password,
            "api_key": PROJECT_API_KEY
        }

        # Attempt to register the user via ARTA
        response = requests.post(ARTA_URL_REGISTER, data=registration_data, verify=False)
        if response.status_code != 200:
            return None


        # Create Django user
        user = User.objects.create(username=mobile, first_name=first_name, last_name=last_name)

        # Generate base order ID
        last_profile = SystemUserProfile.objects.order_by('-base_order').first()
        base_order = (last_profile.base_order + 1) if last_profile else 1000

        # Create system profile
        system_profile = SystemUserProfile.objects.create(
            mobile=mobile,
            first_name=first_name,
            last_name=last_name,
            fullname=f"{first_name} {last_name}",
            user=user,
            base_order=base_order,
            password=password,
            national_id=national_id,
            city=city,
            province=province
        )

    # Create address for the user
    address = SystemAddress.objects.create(
        city=city,
        province=province,
        address=address_text,
        postal_code=postal_code
    )

    # Assign role to the user
    system_profile.role.add(group)

    # Create wallet for the user
    wallet = Wallet.objects.create()

    return {
        "system_profile": system_profile,
        "address": address,
        "wallet": wallet
    }
