"""Enterprise inquiry application service."""
from __future__ import annotations

from typing import Optional
from uuid import UUID

import structlog

from src.core.protocols import OpsNotifierProtocol
from src.domain.billing.inquiry_templates import render_enterprise_inquiry_notification
from src.domain.billing.models import EnterpriseInquiry
from src.domain.billing.repository import EnterpriseInquiryRepository

logger = structlog.get_logger()


class EnterpriseInquiryService:
    def __init__(self, repo: EnterpriseInquiryRepository, notifier: OpsNotifierProtocol):
        self._repo = repo
        self._notifier = notifier

    async def create(
        self,
        *,
        workspace_id: Optional[UUID],
        user_id: Optional[UUID],
        first_name: str,
        last_name: str,
        email: str,
        phone: str,
        website_count: int,
        ai_credit_minutes_desired: int,
        is_agency_account: bool,
        employee_count: int,
        additional_features: Optional[str],
        plan_slug: Optional[str],
    ) -> EnterpriseInquiry:
        return await self._repo.create(
            workspace_id=workspace_id,
            user_id=user_id,
            first_name=first_name,
            last_name=last_name,
            email=email,
            phone=phone,
            website_count=website_count,
            ai_credit_minutes_desired=ai_credit_minutes_desired,
            is_agency_account=is_agency_account,
            employee_count=employee_count,
            additional_features=additional_features,
            plan_slug=plan_slug,
        )

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