package fikoyt_json

import (
	"encoding/json"
	"fmt"
	FikoYTMap "server/sistem/fikoyt_map"

	"github.com/gofiber/fiber/v3"
)

func AraIsleyici() fiber.Handler {
	return func(c fiber.Ctx) error {
		var raw interface{}
		var err error
		fmt.Println(string(c.Body()))
		// Formdan gelen veri varsa onu al, yoksa body'i kullan
		input := []byte(c.FormValue("req_body"))
		if len(input) == 0 {
			input = c.BodyRaw()
		}

		// Eğer hala boşsa hiç parse etmeye çalışma
		if len(input) == 0 {
			c.Locals("json", nil)
			return c.Next()
		}

		// JSON parse işlemi
		err = json.Unmarshal(input, &raw)
		if err != nil {
			// Hatalı JSON varsa yine nil ata
			c.Locals("json", nil)
			return c.Next()
		}

		// Gelen veri map ise
		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:
			// Ne map ne de listeyse olduğu gibi gönder
			c.Locals("json", raw)
		}

		return c.Next()
	}
}
