import logging
from apps.calls.constants import BotType
from apps.companies.models import Company
from apps.appointments.repositories import AppointmentRepository
from apps.appointments.services import AppointmentNotificationService


logger = logging.getLogger(__name__)


class GHLAppointmentService:

    @staticmethod
    def book_ghl_appointment(validated_data):
        company = Company.objects.filter(
            ghl_company_id=validated_data["company_id"]
        ).first()

        if not company:
            raise ValueError("Company not found")

        appointment = AppointmentRepository.create_appointment({
            "name": validated_data.get("customer_name") or "Unknown",
            "appointment_phone": validated_data.get("customer_phone"),
            "scheduled_date": validated_data["appointment_datetime"],
            "company": company,
            "bot_type": BotType.SERVICE_BOT.value,
            "booking_type": validated_data["booking_type"],
            "twilio_call_sid": "webhook-no-call",
        })

        try:
            AppointmentNotificationService.process(appointment)
        except Exception as exc:
            logger.warning(
                "Failed to send appointment notifications for appointment id=%s: %s",
                appointment.id,
                exc
            )
        return appointment
