package api

import (
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type listQuery struct {
	Page    int
	Limit   int
	Offset  int
	Search  string
	Enabled bool
}

func parseListQuery(c *gin.Context) listQuery {
	var q listQuery
	if c == nil {
		return q
	}
	if raw := strings.TrimSpace(c.Query("search")); raw != "" {
		q.Search = raw
		q.Enabled = true
	}
	if raw := strings.TrimSpace(c.Query("page")); raw != "" {
		if v, err := strconv.Atoi(raw); err == nil && v > 0 {
			q.Page = v
		}
		q.Enabled = true
	}
	if raw := strings.TrimSpace(c.Query("limit")); raw != "" {
		if v, err := strconv.Atoi(raw); err == nil && v > 0 {
			q.Limit = v
		}
		q.Enabled = true
	}
	if q.Enabled {
		if q.Limit <= 0 {
			q.Limit = 50
		}
		if q.Limit > 200 {
			q.Limit = 200
		}
		if q.Page <= 0 {
			q.Page = 1
		}
		q.Offset = (q.Page - 1) * q.Limit
	}
	return q
}

func applyListSearch(q *gorm.DB, search string, fields ...string) *gorm.DB {
	if q == nil {
		return q
	}
	search = strings.TrimSpace(search)
	if search == "" || len(fields) == 0 {
		return q
	}
	pattern := "%" + strings.ToLower(search) + "%"
	clauses := make([]string, 0, len(fields))
	args := make([]any, 0, len(fields))
	for _, field := range fields {
		field = strings.TrimSpace(field)
		if field == "" {
			continue
		}
		clauses = append(clauses, "LOWER("+field+") LIKE ?")
		args = append(args, pattern)
	}
	if len(clauses) == 0 {
		return q
	}
	return q.Where(strings.Join(clauses, " OR "), args...)
}

func applyListPagination(q *gorm.DB, query listQuery) *gorm.DB {
	if q == nil {
		return q
	}
	if !query.Enabled {
		return q
	}
	return q.Limit(query.Limit).Offset(query.Offset)
}
