# @File: backend/routers/contact.py
# @Desc: Public endpoints powering the "Contact Us", "Get Prices" and
#        "Support" popup modals on the marketing site. Each endpoint:
#          1) Validates the form payload with Pydantic.
#          2) Builds a plain-text + HTML email body.
#          3) Sends the email via the shared SMTP helper (credentials come
#             from the SMTP_* environment variables the user configured).
#          4) Returns a generic success response to the frontend.
#
#        We intentionally do NOT leak SMTP or server errors to the client —
#        if the backend is misconfigured we log the details and surface a
#        friendly 502 so the UI can display a retry message.
import html
import logging
from typing import Iterable, Tuple

from fastapi import APIRouter, HTTPException

from schemas.contact import (
    ContactFormRequest,
    ContactFormResponse,
    GetPriceRequest,
    SupportFormRequest,
)
from services.email_sender import SmtpConfigError, send_email

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/v1/contact", tags=["contact"])


# Destination mailboxes — these mirror the three public inbox addresses the
# user specified for DoItEasy. If in the future these need to become
# configurable, they can be moved to environment variables.
CONTACT_INBOX = "info@doiteasy.net"
SALES_INBOX = "sales@doiteasy.net"
SUPPORT_INBOX = "support@doiteasy.net"


def _kv_block(fields: Iterable[Tuple[str, str]]) -> Tuple[str, str]:
    """Render a list of ``(label, value)`` pairs into plain-text and HTML bodies."""
    text_lines = []
    html_rows = []
    for label, value in fields:
        safe_value = (value or "—").strip() or "—"
        text_lines.append(f"{label}: {safe_value}")
        html_rows.append(
            f"<tr>"
            f"<td style='padding:6px 14px 6px 0;color:#475569;font-weight:600;white-space:nowrap;'>"
            f"{html.escape(label)}</td>"
            f"<td style='padding:6px 0;color:#0f172a;'>"
            f"{html.escape(safe_value).replace(chr(10), '<br>')}</td>"
            f"</tr>"
        )
    text_body = "\n".join(text_lines)
    html_body = (
        "<table style='border-collapse:collapse;font-family:Arial,Helvetica,sans-serif;"
        "font-size:14px;line-height:1.5;'>"
        + "".join(html_rows)
        + "</table>"
    )
    return text_body, html_body


def _wrap_html(title: str, intro: str, inner_html: str) -> str:
    """Wrap a content block into a branded DoItEasy HTML email shell."""
    return (
        "<div style='background:#f8fafc;padding:24px;font-family:Arial,Helvetica,sans-serif;'>"
        "<div style='max-width:640px;margin:0 auto;background:#ffffff;border-radius:12px;"
        "overflow:hidden;border:1px solid #e2e8f0;'>"
        "<div style='background:#0b6e3e;padding:18px 24px;color:#ffffff;'>"
        f"<h2 style='margin:0;font-size:18px;font-weight:700;'>{html.escape(title)}</h2>"
        "</div>"
        "<div style='padding:22px 24px;color:#0f172a;font-size:14px;line-height:1.6;'>"
        f"<p style='margin:0 0 14px;color:#475569;'>{html.escape(intro)}</p>"
        f"{inner_html}"
        "<p style='margin:22px 0 0;color:#94a3b8;font-size:12px;'>"
        "Sent from the DoItEasy website form."
        "</p>"
        "</div></div></div>"
    )


async def _send_or_fail(
    *,
    to_addr: str,
    subject: str,
    text_body: str,
    html_body: str,
    reply_to: str,
) -> None:
    """Dispatch the email and translate infrastructure errors into HTTP errors."""
    try:
        await send_email(
            to_addrs=[to_addr],
            subject=subject,
            text_body=text_body,
            html_body=html_body,
            reply_to=reply_to,
        )
    except SmtpConfigError as exc:
        logger.error("SMTP misconfiguration while sending %r: %s", subject, exc)
        raise HTTPException(
            status_code=503,
            detail="Email service is not configured yet. Please try again later.",
        ) from exc
    except Exception:
        # Log the full traceback but never leak internals to the public API.
        logger.exception("Failed to send form email: subject=%r to=%s", subject, to_addr)
        raise HTTPException(
            status_code=502,
            detail="We could not deliver your message right now. Please try again shortly.",
        )


@router.post("/contact-us", response_model=ContactFormResponse)
async def submit_contact_form(payload: ContactFormRequest):
    """Send the "Contact Us" popup submission to info@doiteasy.net."""
    subject_line = payload.subject or "Website Contact Form"
    text_body, html_table = _kv_block(
        [
            ("Name", payload.name),
            ("Email", str(payload.email)),
            ("Phone", payload.phone or ""),
            ("Subject", subject_line),
            ("Message", payload.message),
        ]
    )
    html_body = _wrap_html(
        title="New Contact Form Submission",
        intro="A visitor just submitted the Contact Us form on doiteasy.net.",
        inner_html=html_table,
    )
    await _send_or_fail(
        to_addr=CONTACT_INBOX,
        subject=f"[Contact] {subject_line}",
        text_body=f"New contact request from the website:\n\n{text_body}",
        html_body=html_body,
        reply_to=str(payload.email),
    )
    return ContactFormResponse(
        success=True,
        message="Thanks! Our team will get back to you as soon as possible.",
    )


@router.post("/get-price", response_model=ContactFormResponse)
async def submit_get_price_form(payload: GetPriceRequest):
    """Send the "Get Prices" popup submission to sales@doiteasy.net."""
    text_body, html_table = _kv_block(
        [
            ("Name", payload.name),
            ("Email", str(payload.email)),
            ("Phone", payload.phone or ""),
            ("Company", payload.company or ""),
            ("Service of Interest", payload.service or ""),
            ("Message", payload.message or ""),
        ]
    )
    html_body = _wrap_html(
        title="New Pricing / Sales Inquiry",
        intro="A visitor requested pricing information from the website.",
        inner_html=html_table,
    )
    await _send_or_fail(
        to_addr=SALES_INBOX,
        subject=f"[Pricing Inquiry] {payload.service or 'General'}",
        text_body=f"New pricing inquiry from the website:\n\n{text_body}",
        html_body=html_body,
        reply_to=str(payload.email),
    )
    return ContactFormResponse(
        success=True,
        message="Thanks! Our sales team will reach out with a tailored quote shortly.",
    )


@router.post("/support", response_model=ContactFormResponse)
async def submit_support_form(payload: SupportFormRequest):
    """Send the "Support" popup submission to support@doiteasy.net."""
    subject_line = payload.subject or "Website Support Request"
    text_body, html_table = _kv_block(
        [
            ("Name", payload.name),
            ("Email", str(payload.email)),
            ("Phone", payload.phone or ""),
            ("Subject", subject_line),
            ("Message", payload.message),
        ]
    )
    html_body = _wrap_html(
        title="New Support Request",
        intro="A visitor submitted a support request from the website.",
        inner_html=html_table,
    )
    await _send_or_fail(
        to_addr=SUPPORT_INBOX,
        subject=f"[Support] {subject_line}",
        text_body=f"New support request from the website:\n\n{text_body}",
        html_body=html_body,
        reply_to=str(payload.email),
    )
    return ContactFormResponse(
        success=True,
        message="Thanks! Our support team will respond as soon as possible.",
    )