package domain

import (
	"errors"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5/pgtype"
)

var (
	ErrInvalidInterval = errors.New("invalid interval provided")
)

type DateInterval string

var (
	MonthInterval DateInterval = "month"
	WeekInterval  DateInterval = "week"
	DayInterval   DateInterval = "day"
)

func (d DateInterval) IsValid() bool {
	switch d {
	case MonthInterval,
		WeekInterval,
		DayInterval:
		return true
	default:
		return false
	}

}

func ParseDateInterval(val string) (DateInterval, error) {
	d := DateInterval(val)
	if !d.IsValid() {
		return "", fmt.Errorf("invalid date interval: %q", val)
	}
	return d, nil
}

type ValidDateInterval struct {
	Value DateInterval
	Valid bool
}

func (v ValidDateInterval) ToPG() pgtype.Text {
	return pgtype.Text{
		String: string(v.Value),
		Valid:  v.Valid,
	}
}

func ConvertStringPtrInterval(value *string) (ValidDateInterval, error) {
	if value == nil {
		return ValidDateInterval{}, nil
	}

	parsedDateInterval, err := ParseDateInterval(*value)
	if err != nil {
		return ValidDateInterval{}, err
	}

	return ValidDateInterval{
		Value: parsedDateInterval,
		Valid: true,
	}, nil
}

func GetEndDateFromInterval(interval DateInterval, startDate time.Time) (time.Time, error) {
	var endDate time.Time
	switch interval {
	case "day":
		endDate = startDate
	case "week":
		endDate = startDate.AddDate(0, 0, 6) // 7-day window
	case "month":
		endDate = startDate.AddDate(0, 1, -1) // till end of month
	default:
		return time.Time{}, fmt.Errorf("unknown date interval")
	}
	return endDate, nil
}
