"""Email verification for new signups — nobody can log in until they click
the link in their verification email. Applies to customers and pickers;
admin accounts are created out-of-band and are pre-verified."""

import secrets

from django.urls import reverse

from market.emailer import send_email
from market.site_url import absolute_url
from market.sms import send_sms, sms_lang, sms_text

from .supabase_client import get_client


def generate_verification_token():
    return secrets.token_urlsafe(32)


def send_verification_email(request, user):
    verify_url = absolute_url(request, reverse('accounts:verify_email', args=[user['verification_token']]))
    subject = 'Verify your PickkerMarket account'
    body = (
        f"Hi {user.get('first_name') or 'there'},\n\n"
        "Welcome to PickkerMarket — your fresh produce delivery platform.\n\n"
        "Please confirm your email address to activate your account and log in:\n"
        f"{verify_url}\n\n"
        "If you didn't create this account, you can safely ignore this email.\n\n"
        "— The PickkerMarket Team\n"
        "A product of Clanert Sustain Company Limited"
    )
    send_email(user['email'], subject, body)


def send_verification_sms(request, user):
    """Same verification link, sent by SMS too — a phone reliably gets
    checked even when the email lands in spam, and the message says so
    explicitly so the customer knows to go look there instead of assuming
    nothing was sent."""
    verify_url = absolute_url(request, reverse('accounts:verify_email', args=[user['verification_token']]))
    lang = sms_lang(user.get('sms_language'))
    # Short on purpose — the spam-folder note lives in the email, not here.
    send_sms(user.get('phone_number'), sms_text(
        lang,
        f"PickkerMarket: Verify your account: {verify_url}",
        f"PickkerMarket: Thibitisha akaunti yako: {verify_url}",
    ))


def verify_token(token):
    """Marks the matching user verified and returns their row, or None if the
    token doesn't match anyone."""
    client = get_client()
    resp = client.table('pickker_users').select('*').eq('verification_token', token).execute()
    if not resp.data:
        return None
    user = resp.data[0]
    if not user['is_verified']:
        client.table('pickker_users').update({'is_verified': True}).eq('id', user['id']).execute()
        user['is_verified'] = True
    return user


def resend_verification_email(request, email):
    """Returns True if a verification email was (re)sent, False if there's no
    matching unverified account."""
    client = get_client()
    resp = client.table('pickker_users').select('*').eq('email', email).execute()
    if not resp.data:
        return False
    user = resp.data[0]
    if user['is_verified']:
        return False
    if not user.get('verification_token'):
        token = generate_verification_token()
        client.table('pickker_users').update({'verification_token': token}).eq('id', user['id']).execute()
        user['verification_token'] = token
    send_verification_email(request, user)
    send_verification_sms(request, user)
    return True
