package seatbilling

import (
	"context"
	"database/sql"
	"fmt"
	"time"

	"github.com/tidbcloud/AgentTeam/internal/coredb"
	"github.com/tidbcloud/AgentTeam/internal/quota"
)

func loadActiveSeatGrantSummary(ctx context.Context, queryer coredb.QueryRower, organizationID string, now time.Time) (int64, *time.Time, error) {
	var seats sql.NullInt64
	var nextExpiresAt sql.NullTime
	if err := queryer.QueryRow(ctx, `
SELECT COALESCE(SUM(limit_delta), 0), MIN(expires_at)
FROM organization_resource_quota_grants
WHERE organization_id = $1
  AND metric = $3
  AND quota_scope = $4
  AND revoked_at IS NULL
  AND (expires_at IS NULL OR $2 < expires_at)
`, organizationID, now.UTC(), quota.MetricSeats, quota.ScopeOrganization).Scan(&seats, &nextExpiresAt); err != nil {
		return 0, nil, fmt.Errorf("load active seat grants: %w", err)
	}
	var expiresAt *time.Time
	if nextExpiresAt.Valid {
		copy := nextExpiresAt.Time.UTC()
		expiresAt = &copy
	}
	return seats.Int64, expiresAt, nil
}

func loadActiveAgentOwnerGrantSummary(ctx context.Context, queryer coredb.QueryRower, organizationID string, now time.Time) (int64, error) {
	var agents sql.NullInt64
	if err := queryer.QueryRow(ctx, `
SELECT COALESCE(SUM(limit_delta), 0)
FROM organization_resource_quota_grants
WHERE organization_id = $1
  AND metric = $3
  AND quota_scope = $4
  AND revoked_at IS NULL
  AND (expires_at IS NULL OR $2 < expires_at)
`, organizationID, now.UTC(), quota.MetricAgents, quota.ScopeAgentOwner).Scan(&agents); err != nil {
		return 0, fmt.Errorf("load active agent owner grants: %w", err)
	}
	return agents.Int64, nil
}
