package billing

import (
	"context"
	"errors"
	"time"

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

type usageRepository interface {
	incrementDaily(ctx context.Context, networkID string, at time.Time) error
	getDaily(ctx context.Context, networkID string, at time.Time) (int, error)
}

type usageRepositoryImpl struct {
	pool *pgxpool.Pool
}

func newUsageRepository(pool *pgxpool.Pool) usageRepository {
	return &usageRepositoryImpl{pool: pool}
}

func (r *usageRepositoryImpl) incrementDaily(ctx context.Context, networkID string, at time.Time) error {
	_, err := r.pool.Exec(ctx, `
		INSERT INTO network_message_usage (network_id, usage_date, message_count, updated_at)
		VALUES ($1, ($2 AT TIME ZONE 'UTC')::date, 1, NOW())
		ON CONFLICT (network_id, usage_date) DO UPDATE
		SET message_count = network_message_usage.message_count + 1,
		    updated_at    = NOW()
	`, networkID, at)
	return err
}

func (r *usageRepositoryImpl) getDaily(ctx context.Context, networkID string, at time.Time) (int, error) {
	var count int
	err := r.pool.QueryRow(ctx, `
		SELECT message_count FROM network_message_usage
		WHERE network_id = $1 AND usage_date = ($2 AT TIME ZONE 'UTC')::date
	`, networkID, at).Scan(&count)
	if errors.Is(err, pgx.ErrNoRows) {
		return 0, nil
	}
	if err != nil {
		return 0, err
	}
	return count, nil
}
