package inviteemailratelimit

import (
	"context"
	"time"

	"github.com/gocql/gocql"
	"go.uber.org/zap"
)

// GetDailyEmailCount returns the number of invitation emails sent by a user on the given date.
// Returns 0 if no record exists (user hasn't sent any invites today).
func (r *repositoryImpl) GetDailyEmailCount(ctx context.Context, userID gocql.UUID, date time.Time) (int, error) {
	r.logger.Debug("Getting daily email count",
		zap.String("user_id", userID.String()),
		zap.Time("date", date))

	// Normalize date to midnight UTC
	dateOnly := date.UTC().Truncate(24 * time.Hour)

	var count int64
	query := r.session.Query(`
		SELECT emails_sent_today
		FROM invite_email_rate_limits_by_user_id_and_date
		WHERE user_id = ? AND date = ?
	`, userID, dateOnly).WithContext(ctx)

	if err := query.Scan(&count); err != nil {
		if err == gocql.ErrNotFound {
			// No record means no emails sent today
			return 0, nil
		}
		r.logger.Error("Failed to get daily email count",
			zap.String("user_id", userID.String()),
			zap.Error(err))
		return 0, err
	}

	return int(count), nil
}
