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

		// Önce form verisini dene
		reqBody := c.FormValue("req_body")
		input := []byte(reqBody)
		if reqBody == "" {
			input = c.Body() // Form yoksa gövdeyi kullan
		}

		err = json.Unmarshal(input, &raw)
		if err != nil {
			// Parse edilemiyorsa hiç bir şey yapma, nil gönder
			fmt.Println(err.Error(), raw)
			c.Locals("json", nil)
			return c.Next()
		}

		// Gelen JSON'un türüne göre işlem yap
		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 obje ne listeyse direkt yolla
			c.Locals("json", raw)
		}

		return c.Next()
	}
}
