from __future__ import annotations

import logging

from sqlalchemy.orm import Session

from app.config import get_settings
from app.database import SessionLocal, release_db_connection
from app.models import User, UserRole
from app.models_admin import ContactMessage
from app.schemas import ContactMessageCreateRequest
from app.services.email_otp import _send_email

logger = logging.getLogger(__name__)


def resolve_admin_notify_email(db: Session) -> str | None:
    settings = get_settings()
    configured = (settings.admin_notify_email or "").strip()
    if configured:
        return configured

    smtp_from = (settings.smtp_from or "").strip()
    if smtp_from:
        return smtp_from

    admin = (
        db.query(User)
        .filter(User.role == UserRole.admin, User.is_active.is_(True))
        .order_by(User.id.asc())
        .first()
    )
    if admin and admin.email:
        return admin.email.strip()
    return None


def create_contact_message(db: Session, body: ContactMessageCreateRequest) -> ContactMessage:
    row = ContactMessage(
        full_name=body.full_name.strip(),
        email=str(body.email).strip(),
        phone_number=body.phone_number.strip() if body.phone_number else None,
        subject=body.subject.strip(),
        message=body.message.strip(),
        email_sent=False,
    )
    db.add(row)
    db.commit()
    db.refresh(row)
    return row


async def send_contact_message_to_admin(
    db: Session,
    contact: ContactMessage,
    *,
    admin_email: str | None = None,
) -> bool:
    recipient = admin_email or resolve_admin_notify_email(db)
    if not recipient:
        logger.warning("No admin notify email configured for contact message id=%s", contact.id)
        return False

    phone_line = contact.phone_number or "Not provided"
    plain = (
        "New contact form submission — Pole Power Academy\n\n"
        f"Name: {contact.full_name}\n"
        f"Email: {contact.email}\n"
        f"Phone: {phone_line}\n"
        f"Subject: {contact.subject}\n\n"
        f"Message:\n{contact.message}\n"
    )
    html = (
        "<h2>New contact form submission</h2>"
        f"<p><strong>Name:</strong> {contact.full_name}</p>"
        f"<p><strong>Email:</strong> {contact.email}</p>"
        f"<p><strong>Phone:</strong> {phone_line}</p>"
        f"<p><strong>Subject:</strong> {contact.subject}</p>"
        f"<p><strong>Message:</strong></p><p>{contact.message.replace(chr(10), '<br>')}</p>"
    )

    release_db_connection(db)
    sent = await _send_email(
        to_email=recipient,
        subject=f"Contact form: {contact.subject}",
        body=plain,
        html_body=html,
    )
    if sent:
        contact.email_sent = True
        update_db = SessionLocal()
        try:
            row = update_db.get(ContactMessage, contact.id)
            if row is not None:
                row.email_sent = True
                update_db.commit()
        finally:
            update_db.close()
    return sent


async def send_contact_confirmation_to_client(contact: ContactMessage) -> bool:
    """Send a thank-you / copy of the enquiry to the person who submitted the form."""
    client_email = (contact.email or "").strip()
    if not client_email:
        logger.warning("No client email for contact confirmation id=%s", contact.id)
        return False

    phone_line = contact.phone_number or "Not provided"
    plain = (
        f"Hi {contact.full_name},\n\n"
        "Thank you for contacting Pole Power Academy. We have received your message "
        "and will get back to you as soon as possible (usually within one business day).\n\n"
        "Here is a copy of what you sent:\n\n"
        f"Subject: {contact.subject}\n"
        f"Phone: {phone_line}\n\n"
        f"{contact.message}\n\n"
        "— Pole Power Academy\n"
    )
    html = (
        f"<p>Hi {contact.full_name},</p>"
        "<p>Thank you for contacting <strong>Pole Power Academy</strong>. We have received "
        "your message and will get back to you as soon as possible "
        "(usually within one business day).</p>"
        "<p><strong>Your message:</strong></p>"
        f"<p><strong>Subject:</strong> {contact.subject}<br>"
        f"<strong>Phone:</strong> {phone_line}</p>"
        f"<p>{contact.message.replace(chr(10), '<br>')}</p>"
        "<p>— Pole Power Academy</p>"
    )

    return await _send_email(
        to_email=client_email,
        subject=f"We received your message: {contact.subject}",
        body=plain,
        html_body=html,
    )


def list_contact_messages(db: Session, *, skip: int = 0, limit: int = 50) -> tuple[list[ContactMessage], int]:
    q = db.query(ContactMessage).order_by(ContactMessage.created_at.desc())
    total = q.count()
    rows = q.offset(skip).limit(limit).all()
    return rows, total
