import frappe
from frappe import _
from frappe.rate_limiter import rate_limit


@frappe.whitelist(allow_guest=True)
@rate_limit(limit=5, seconds=300)  # 5 attempts per 5 minutes
def register_user(email, password, full_name, voen=None):
    """
    Register a new user for Cloud Portal.
    Creates a user with Website User role.
    """
    # Validate inputs
    if not email or not password or not full_name:
        return {
            "success": False,
            "message": _("Please provide email, password and full name")
        }

    # Validate input lengths to prevent abuse
    email = email.strip()[:254]  # Max email length per RFC
    full_name = full_name.strip()[:140]  # Reasonable name length

    # Check if email is valid
    if not frappe.utils.validate_email_address(email):
        return {
            "success": False,
            "message": _("Please enter a valid email address")
        }

    # Check if user already exists
    if frappe.db.exists("User", email):
        return {
            "success": False,
            "message": _("User with this email already exists")
        }

    # Password will be validated by Frappe's password policy

    try:
        # Parse full name once for efficiency
        name_parts = full_name.split()
        first_name = name_parts[0] if name_parts else email
        last_name = " ".join(name_parts[1:]) if len(name_parts) > 1 else ""

        # Create user
        user = frappe.get_doc({
            "doctype": "User",
            "email": email,
            "first_name": first_name,
            "last_name": last_name,
            "enabled": 1,
            "new_password": password,
            "send_welcome_email": 0,
            "user_type": "Website User"
        })

        user.flags.ignore_permissions = True
        user.insert()

        # Add Website User role
        user.add_roles("Website User")

        # Create ERPNext Customer linked to this user
        customer = frappe.get_doc({
            "doctype": "Customer",
            "customer_name": full_name,
            "customer_type": "Individual",
            "tax_id": voen or "",
            "portal_users": [{"user": email}],
        })
        customer.flags.ignore_permissions = True
        customer.insert()

        frappe.db.commit()

        # Auto-login after registration
        frappe.local.login_manager.login_as(email)

        return {
            "success": True,
            "message": _("Account created successfully"),
            "user": email
        }

    except frappe.exceptions.ValidationError as e:
        return {
            "success": False,
            "message": str(e)
        }
    except Exception as e:
        frappe.log_error(f"Registration error: {str(e)}", "Cloud Portal Registration")
        return {
            "success": False,
            "message": _("Registration failed. Please try again.")
        }
