package fikoyt_json

import (
	"encoding/json"
	FikoYTMap "server/sistem/fikoyt_map"

	"github.com/gofiber/fiber/v3"
)

func AraIsleyici() fiber.Handler {
	return func(c fiber.Ctx) error {
		var raw interface{}
		reqBody := c.FormValue("req_body")
		var err error

		// Önce form verisini dene
		if reqBody != "" {
			err = json.Unmarshal([]byte(reqBody), &raw)
		}

		// Form başarısızsa body'yi dene
		if err != nil || reqBody == "" {
			err = json.Unmarshal(c.Body(), &raw)
			if err != nil {
				// Parse edilemiyorsa hiç bir şey yapma, nil gönder
				c.Locals("json", nil)
				return c.Next()
			}
		}

		switch val := raw.(type) {
		case map[string]interface{}:
			c.Locals("json", FikoYTMap.FikoYTMap(val))
		case []interface{}:
			var list []FikoYTMap.FikoYTMap
			for _, item := range val {
				if m, ok := item.(map[string]interface{}); ok {
					list = append(list, FikoYTMap.FikoYTMap(m))
				}
			}
			c.Locals("json", list)
		default:
			// Obje ya da liste değilse: gelen veriyi direkt gönder
			c.Locals("json", raw)
		}

		return c.Next()
	}
}
