package bootable

import (
	"strings"
	"time"

	"git.simanc.com/software/golib/v4/features/mo"
	"git.simanc.com/software/golib/v4/infra/ii"
)

const (
	TimeLayout = "2006-01-02"
)

var (
	fixedDayHour, _ = time.ParseDuration("23h59m59s999ms")
)

func (q *Filter) handleDateTimeFrom(layout, time string) (start mo.DateTime, end mo.DateTime, err error) {
	start, err = mo.ResolveDateTimeFrom(layout, time)
	if err != nil {
		return 0, 0, err
	}
	end = mo.NewDateTimeFromTime(start.Time().Add(fixedDayHour))
	return start, end, nil
}

func (q *Filter) handleDateTimeRange(layout, start, end string) (mo.DateTime, mo.DateTime, error) {
	started, err := mo.ResolveDateTimeFrom(layout, start)
	if err != nil {
		return 0, 0, err
	}
	_, ended, err := q.handleDateTimeFrom(layout, end)
	if err != nil {
		return 0, 0, err
	}
	return started, ended, nil
}

func (q *Filter) handleDateTime(matcher *mo.Matcher, field ii.FieldInfo, value any) {
	switch v := value.(type) {
	case string:
		v = strings.TrimSpace(v)
		var (
			start, end mo.DateTime
			err        error
		)
		before, after, ok := strings.Cut(v, " ")
		if ok {
			start, end, err = q.handleDateTimeRange(TimeLayout, before, after)
		} else {
			start, end, err = q.handleDateTimeFrom(TimeLayout, v)
		}
		if err != nil {
			return
		}
		matcher.Gte(field.Name, start)
		matcher.Lte(field.Name, end)
	default:
		if t, err := field.Convert(value); err == nil {
			matcher.Gte(field.Name, t)
		}
	}
}
