from .models import Booking, Service, Contact
from datetime import datetime, timedelta

def create_booking(contact_phone_number: str, service_name: str, booking_time_str: str) -> str:
    """
    Creates a booking for a given service at a specific time.
    """
    try:
        contact = Contact.objects.get(phone_number=contact_phone_number)
        service = Service.objects.get(name__iexact=service_name)
        booking_time = datetime.fromisoformat(booking_time_str)

        end_time = booking_time + timedelta(minutes=service.duration)

        booking = Booking.objects.create(
            contact=contact,
            service=service,
            start_time=booking_time,
            end_time=end_time,
            status='scheduled',
        )
        return f"Booking confirmed for {service.name} at {booking_time.strftime('%Y-%m-%d %H:%M')}."
    except Contact.DoesNotExist:
        return "Error: Contact not found."
    except Service.DoesNotExist:
        return f"Error: Service '{service_name}' not found."
    except Exception as e:
        return f"Error: Could not create booking. {e}"
