package utils

import (
	"strings"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
)

func CurrentEpoch() int64 {
	return time.Now().Unix()
}

func CurrentISTEpoch() int64 {
	loc, err := time.LoadLocation("Asia/Kolkata")
	if err != nil {
		return time.Now().Unix()
	}
	return time.Now().In(loc).Unix()
}

// ISTLocation returns Asia/Kolkata, falling back to a fixed +05:30 zone
// when tzdata is not available on the host.
func ISTLocation() *time.Location {
	loc, err := time.LoadLocation("Asia/Kolkata")
	if err != nil {
		return time.FixedZone("IST", 5*60*60+30*60)
	}
	return loc
}

func StringToObjectID(id string) (bson.ObjectID, error) {
	objectID, err := bson.ObjectIDFromHex(id)
	if err != nil {
		return bson.NilObjectID, err
	}

	return objectID, nil
}

func MidnightHourSecond() int64 {
	loc, err := time.LoadLocation("Asia/Kolkata")
	if err != nil {
		loc = time.FixedZone("IST", 5*60*60+30*60)
	}

	now := time.Now().In(loc)
	midnight := time.Date(
		now.Year(), now.Month(), now.Day(),
		0, 0, 0, 0, loc,
	)

	return midnight.Unix()
}

// EpochToDateString formats the epoch as dd/MM/yyyy in IST, e.g. 09/06/2026
func EpochToDateString(epoch int64) string {
	return time.Unix(epoch, 0).In(ISTLocation()).Format("02/01/2006")
}

// SplitPath returns the non blank ids of a path like ",id1,id2,"
func SplitPath(path string) []string {
	var ids []string
	for id := range strings.SplitSeq(path, ",") {
		id = strings.TrimSpace(id)
		if id != "" {
			ids = append(ids, id)
		}
	}
	return ids
}
