"""
mail.py — Asynkron mail-sending via aiosmtplib.
I udvikling bruges MailHog som SMTP-server.
"""
import asyncio
import secrets
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import aiosmtplib
from app.core.config import settings


def generate_verify_token() -> str:
    return secrets.token_urlsafe(32)


async def send_verification_email(email: str, username: str, token: str):
    verify_url = f"{settings.BASE_URL}/auth/verify/{token}"

    msg = MIMEMultipart("alternative")
    msg["Subject"] = "Bekræft din LineDance-konto"
    msg["From"]    = settings.MAIL_FROM
    msg["To"]      = email

    text = f"""Hej {username},

Tak for at oprette en konto på LineDance Player.

Klik på linket nedenfor for at bekræfte din e-mailadresse:
{verify_url}

Linket udløber ikke — men kontoen er ikke aktiv før du har bekræftet.

Hilsen
LineDance Player
"""

    html = f"""<html><body>
<h2>Velkommen til LineDance Player, {username}!</h2>
<p>Klik på knappen nedenfor for at bekræfte din e-mailadresse:</p>
<p>
  <a href="{verify_url}"
     style="background:#e8a020;color:#111;padding:12px 24px;
            border-radius:6px;text-decoration:none;font-weight:bold;">
    Bekræft e-mail
  </a>
</p>
<p>Eller kopier dette link:<br>
<a href="{verify_url}">{verify_url}</a></p>
<p>Linket udløber ikke.</p>
</body></html>"""

    msg.attach(MIMEText(text, "plain", "utf-8"))
    msg.attach(MIMEText(html, "html", "utf-8"))

    try:
        await aiosmtplib.send(
            msg,
            hostname=settings.MAIL_HOST,
            port=settings.MAIL_PORT,
            username=settings.MAIL_USERNAME or None,
            password=settings.MAIL_PASSWORD or None,
            start_tls=settings.MAIL_TLS,   # STARTTLS på port 587
            use_tls=False,
        )
    except Exception as e:
        print(f"Mail-fejl: {e}")
        raise  # Vis fejlen i serverlogs


async def send_share_invitation(email: str, owner_name: str,
                                 playlist_name: str, permission: str,
                                 accept_url: str):
    perm_text = {"view": "se", "copy": "kopiere", "edit": "redigere"}.get(permission, "se")

    msg = MIMEMultipart("alternative")
    msg["Subject"] = f"{owner_name} har delt en danseliste med dig"
    msg["From"]    = settings.MAIL_FROM
    msg["To"]      = email

    html = f"""<html><body>
<h2>Du er inviteret!</h2>
<p>{owner_name} har delt danselisten <strong>{playlist_name}</strong> med dig.</p>
<p>Du har fået adgang til at <strong>{perm_text}</strong> listen.</p>
<p>
  <a href="{accept_url}"
     style="background:#e8a020;color:#111;padding:12px 24px;
            border-radius:6px;text-decoration:none;font-weight:bold;">
    Se danseliste
  </a>
</p>
</body></html>"""

    msg.attach(MIMEText(html, "html", "utf-8"))
    try:
        await aiosmtplib.send(
            msg,
            hostname=settings.MAIL_HOST,
            port=settings.MAIL_PORT,
            use_tls=settings.MAIL_TLS,
        )
    except Exception as e:
        print(f"Mail-fejl (share): {e}")
