package middlewares

import (
	"encoding/json"
	"strings"

	"github.com/gofiber/fiber/v2"
)

// operatingCityPrefixes maps supported 3-digit pincode prefixes to city names.
var operatingCityPrefixes = map[string]string{
	"641": "Coimbatore",
	"600": "Chennai",
	"560": "Bengaluru",
	"500": "Hyderabad",
}

// CityGateMiddleware rejects bookings from pincodes outside Doormile's operating cities.
// It reads pickuppincode from the JSON body without consuming it, so the downstream
// controller can still call c.BodyParser() as usual.
func CityGateMiddleware(c *fiber.Ctx) error {
	var body struct {
		Pickuppincode string `json:"pickuppincode"`
	}
	if err := json.Unmarshal(c.Body(), &body); err != nil || body.Pickuppincode == "" {
		return c.Next()
	}

	pincode := strings.TrimSpace(body.Pickuppincode)
	if len(pincode) >= 3 {
		if _, ok := operatingCityPrefixes[pincode[:3]]; ok {
			return c.Next()
		}
	}

	return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
		"error": "We are not yet operating in your city. Stay tuned!",
		"code":  "CITY_NOT_SUPPORTED",
	})
}
