# FILE: src/apps/public/services/plot_inquiry_service.py
from __future__ import annotations

import secrets
from datetime import datetime, timezone

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from src.apps.plots.models.plot import Plot
from src.apps.public.models.plot_inquiry import PlotInquiry
from src.core.exceptions import ValidationError

_ALPHANUM = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"  # unambiguous chars only


class PlotInquiryService:
    @staticmethod
    def _generate_reference_id() -> str:
        """Non-sequential reference so inquiry volume can't be enumerated (PRD A04/SEC-11)."""
        year = datetime.now(timezone.utc).year
        suffix = "".join(secrets.choice(_ALPHANUM) for _ in range(6))
        return f"INQ-PLOT-{year}-{suffix}"

    @staticmethod
    async def create(
        db: AsyncSession, tenant_id, body, ip_address=None, user_agent=None
    ) -> PlotInquiry:
        if body.plot_id is not None:
            result = await db.execute(
                select(Plot.id).where(Plot.id == body.plot_id, Plot.tenant_id == tenant_id)
            )
            if result.scalar_one_or_none() is None:
                raise ValidationError("plot_id does not belong to this cemetery")

        inq = PlotInquiry(
            tenant_id=tenant_id,
            plot_id=body.plot_id,
            plot_ref=body.plot_ref,
            sender_name=body.sender_name,
            sender_email=str(body.sender_email) if body.sender_email else None,
            sender_phone=body.sender_phone,
            relationship_=body.relationship,
            preferred_contact_time=body.preferred_contact_time,
            message=body.message,
            reference_id=PlotInquiryService._generate_reference_id(),
            ip_address=ip_address,
            user_agent=user_agent,
            status="new",
        )
        db.add(inq)
        await db.flush()
        return inq
