package query_params

import (
	"strings"

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

type Ordering struct {
	Column string
	IsDesc bool
}

func ParseOrdering[T any](c fiber.Ctx, columnMapping ...map[string]string) ([]Ordering, error) {
	param := c.Query("sort")
	if len(param) < 1 {
		return []Ordering{}, nil
	}

	rules := strings.Split(param, ";")
	var orderings []Ordering
	for _, r := range rules {
		ord, err := parseOrderingRule[T](r, columnMapping...)
		if err != nil {
			continue
		}
		orderings = append(orderings, ord)
	}
	return orderings, nil
}

func parseOrderingRule[T any](rule string, columnMapping ...map[string]string) (Ordering, error) {
	var desc bool
	if key, descStr, ok := strings.Cut(rule, ","); ok {
		switch {
		case strings.Compare(descStr, "desc") == 0:
			desc = true
		case strings.Compare(descStr, "asc") == 0:
			desc = false
		default:
			desc = true
		}
		if col, err := MapParamsKeyToDbColumn[T](key, columnMapping...); err == nil {
			return Ordering{
				Column: col,
				IsDesc: desc,
			}, nil
		} else {
			return Ordering{}, err
		}
	} else {
		if col, err := MapParamsKeyToDbColumn[T](key, columnMapping...); err == nil {
			return Ordering{
				Column: col,
				IsDesc: true,
			}, nil
		} else {
			return Ordering{}, err
		}
	}
}

// func addDefaultOrderingIfNeeded[T any](previousOrderings *[]Ordering, model T) {
// 	newOrderings := new([]Ordering)
// 	var t T
// 	if len(*previousOrderings) < 1 {
// 		if col, err := mreflect.GetGormColumnFromJsonField("id", reflect.TypeOf(t)); err == nil {
// 			*newOrderings = append(*newOrderings, Ordering{
// 				Column: mreflect.GetTableName[T]() + "." + col,
// 				IsDesc: true,
// 			})
// 		}
// 		if col, err := mreflect.GetGormColumnFromJsonField("iso_code", reflect.TypeOf(t)); err == nil {
// 			*newOrderings = append(*newOrderings, Ordering{
// 				Column: mreflect.GetTableName[T]() + "." + col,
// 				IsDesc: false,
// 			})
// 		}
// 		*newOrderings = append(*newOrderings, *previousOrderings...)
// 		*previousOrderings = *newOrderings
// 	}
// }
