package handlers

import (
	"database/sql"
	"encoding/json"
	"html/template"
	"net/http"
	"strconv"
	"time"

	"decor-by-hannahs/internal/auth"
	"decor-by-hannahs/internal/db"
)

func BookingPageHandler(q *db.Queries, tmpl *template.Template) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		type data struct {
			Title      string
			ActivePage string
		}
		_ = tmpl.ExecuteTemplate(w, "booking.tmpl", data{Title: "Book a Service", ActivePage: "booking"})
	}
}

func BookingAPIHandler(q *db.Queries, tmpl *template.Template) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Method is not allowed", http.StatusMethodNotAllowed)
			return
		}

		user, err := auth.GetUser(r.Context())
		if err != nil {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		var in struct {
			ServiceID string `json:"service_id"`
			EventDate string `json:"event_date"`
			Address   string `json:"address"`
			Notes     string `json:"notes"`
		}
		if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
			http.Error(w, "Bad request", http.StatusBadRequest)
			return
		}
		eventTime, err := time.Parse(time.RFC3339, in.EventDate)
		if err != nil {
			http.Error(w, "Invalid date", http.StatusBadRequest)
			return
		}

		svc, err := strconv.ParseInt(in.ServiceID, 10, 64)
		if err != nil {
			http.Error(w, "Invalid Service ID", http.StatusBadRequest)
			return
		}
		svcID := sql.NullInt64{Int64: svc, Valid: true}
		userID := sql.NullInt64{Int64: user.ID, Valid: true}

		booking, err := q.CreateBooking(r.Context(), db.CreateBookingParams{
			UserID:    userID,
			ServiceID: svcID,
			EventDate: eventTime,
			Address:   sqlNullString(in.Address),
			Notes:     sqlNullString(in.Notes),
			Status:    sql.NullString{String: "pending", Valid: true},
		})
		if err != nil {
			http.Error(w, "Failed to create booking", http.StatusInternalServerError)
			return
		}
		writeJSON(w, booking)
	}
}
