"""Website contact inquiry application service."""
from __future__ import annotations

from typing import Optional

import structlog

from src.core.protocols import OpsNotifierProtocol
from src.domain.public.models import ContactInquiry
from src.domain.public.repository import ContactInquiryRepository
from src.domain.public.templates import render_contact_notification

logger = structlog.get_logger()


class ContactInquiryService:
    def __init__(self, repo: ContactInquiryRepository, notifier: OpsNotifierProtocol):
        self._repo = repo
        self._notifier = notifier

    async def create(
        self,
        *,
        first_name: str,
        last_name: str,
        email: str,
        company: Optional[str],
        subject: str,
        message: str,
    ) -> ContactInquiry:
        return await self._repo.create(
            first_name=first_name,
            last_name=last_name,
            email=email,
            company=company,
            subject=subject,
            message=message,
        )

    async def notify_admins(self, row: ContactInquiry) -> None:
        subject, html, text = render_contact_notification(row)
        try:
            await self._notifier.notify(
                subject=subject,
                html=html,
                text=text,
                reply_to=row.email,
            )
        except Exception:
            logger.exception(
                "contact_inquiry_notify_failed",
                inquiry_id=str(row.id),
            )
