import secrets
from datetime import datetime
from flask import url_for
from app.extensions import db
from app.models.user import User
from app.services.email_service import send_templated_email
from app.utils.security import is_valid_name, is_disposable_email, is_valid_mobile


def register_user(data):
    username = data.get("username", "").strip()
    password = data.get("password", "").strip()
    full_name = data.get("full_name", "").strip()
    email = data.get("email", "").strip()
    mobile_number = data.get("mobile_number", "").strip()

    if not username or not password or not full_name or not email or not mobile_number:
        return None, "All fields are required"

    if not is_valid_name(full_name):
        return None, "Invalid full name. Avoid using URLs or special characters."

    if is_disposable_email(email):
        return None, "Disposable or temporary email addresses are not allowed."

    if not is_valid_mobile(mobile_number):
        return None, "Invalid mobile number format."

    existing_user = User.query.filter((User.username == username) | (User.email == email)).first()
    if existing_user:
        return None, "Username or email already exists."

    user = User(
        username=username,
        full_name=full_name,
        email=email,
        mobile_number=mobile_number,
        access_level="member",
        account_status="Not Approved",
    )
    user.set_password(password)
    db.session.add(user)
    db.session.commit()

    send_templated_email(
        to=email,
        subject="Registration Successful - Pending Activation",
        template="emails/registration_pending.html",
        cc_admin=True,
        full_name=full_name,
    )

    return user, None


def reset_password(email):
    user = User.query.filter_by(email=email).first()
    if not user:
        return None, "Email not found."

    new_password = secrets.token_urlsafe(8)
    user.set_password(new_password)
    db.session.commit()

    login_url = url_for("api.auth_login", _external=True)
    send_templated_email(
        to=email,
        subject="Password Reset",
        template="emails/password_reset.html",
        cc_admin=False,
        new_password=new_password,
        login_url=login_url,
        user_full_name=user.full_name,
    )

    return user, None


def approve_user(user, approve=True, access_level=None):
    user.account_status = "Approved" if approve else "Not Approved"
    if access_level:
        user.access_level = access_level
    db.session.commit()
    return user
