package timeutil

import (
	"time"

	"gordenko.dev/dima/qb"
	"gordenko.dev/dima/qb/proto"
)

func FirstSecondInPeriod(since time.Time, period string) (_ time.Time) {
	y, m, d := since.Date()

	switch period {
	case "h":
		h := since.Hour()
		return time.Date(y, m, d, h, 0, 0, 0, time.Local)
	case "d":
		return time.Date(y, m, d, 0, 0, 0, 0, time.Local)
	case "m":
		return time.Date(y, m, 1, 0, 0, 0, 0, time.Local)
	default:
		return since
	}
}

func LastSecondInPeriod(until time.Time, period string) (_ time.Time) {
	y, m, d := until.Date()

	switch period {
	case "h":
		h := until.Hour()
		return time.Date(y, m, d, h, 59, 59, 0, time.Local)
	case "d":
		return time.Date(y, m, d, 23, 59, 59, 0, time.Local)
	case "m":
		tm := time.Date(y, m, 1, 23, 59, 59, 0, time.Local)
		// Додаю місяць
		tm = tm.AddDate(0, 1, 0)
		// Віднімаю день
		return tm.AddDate(0, 0, -1)
	default:
		return until
	}
}

func TimeBoundsOfAggregation(since, until proto.TimeBound, groupBy qb.GroupBy, firstHourOfDay int) (s time.Time, u time.Time) {
	switch groupBy {
	case qb.GroupByHour, qb.GroupByDay:
		s = time.Date(since.Year, since.Month, since.Day, 0, 0, 0, 0, time.Local)
		u = time.Date(until.Year, until.Month, until.Day, 0, 0, 0, 0, time.Local)

	case qb.GroupByMonth:
		s = time.Date(since.Year, since.Month, 1, 0, 0, 0, 0, time.Local)
		u = time.Date(until.Year, until.Month, 1, 0, 0, 0, 0, time.Local)
	}

	if firstHourOfDay > 0 {
		duration := time.Duration(firstHourOfDay) * time.Hour
		s = s.Add(duration)
		u = u.Add(duration)
	}

	u = u.Add(-1 * time.Second)
	return
}
