package bookings

import (
	"errors"
	"strconv"
	"strings"
	"time"
)

// ErrPastClosing is returned by checkClosingHours when the booking's end time
// exceeds the working hours closing time for that day.
var ErrPastClosing = errors.New("booking extends beyond closing hours")

// checkClosingHours verifies that a booking end time (in Europe/London wall-clock
// time) does not exceed the closing time stored as "HH:MM" in the working_hours
// table. Returns ErrPastClosing if the booking runs past close, or a generic
// error if closeStr cannot be parsed.
func checkClosingHours(localEnd time.Time, closeStr string) error {
	parts := strings.Split(closeStr, ":")
	if len(parts) < 2 {
		return errors.New("invalid closing time format")
	}
	closeHour, err := strconv.Atoi(parts[0])
	if err != nil {
		return errors.New("invalid closing time format")
	}
	closeMin, err := strconv.Atoi(parts[1])
	if err != nil {
		return errors.New("invalid closing time format")
	}
	if localEnd.Hour() > closeHour || (localEnd.Hour() == closeHour && localEnd.Minute() > closeMin) {
		return ErrPastClosing
	}
	return nil
}
