package publicshare

import (
	"context"
	"strings"
	"time"

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

// AccessStats tracks anonymous public link usage via Ulti API.
type AccessStats struct {
	FirstAccessAt time.Time
	LastAccessAt  time.Time
	AccessCount   int64
}

// RecordAccess bumps usage counters for a public share token.
func RecordAccess(ctx context.Context, db *pgxpool.Pool, token string) {
	if db == nil {
		return
	}
	token = strings.TrimSpace(token)
	if token == "" {
		return
	}
	_, _ = db.Exec(ctx, `
		INSERT INTO drive_public_share_access (token, first_access_at, last_access_at, access_count)
		VALUES ($1, NOW(), NOW(), 1)
		ON CONFLICT (token) DO UPDATE SET
			last_access_at = NOW(),
			access_count = drive_public_share_access.access_count + 1
	`, token)
}

// Lookup returns access stats keyed by token.
func Lookup(ctx context.Context, db *pgxpool.Pool, tokens []string) (map[string]AccessStats, error) {
	out := make(map[string]AccessStats)
	if db == nil || len(tokens) == 0 {
		return out, nil
	}
	rows, err := db.Query(ctx, `
		SELECT token, first_access_at, last_access_at, access_count
		FROM drive_public_share_access
		WHERE token = ANY($1::text[])
	`, tokens)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var token string
		var stats AccessStats
		if err := rows.Scan(&token, &stats.FirstAccessAt, &stats.LastAccessAt, &stats.AccessCount); err != nil {
			return nil, err
		}
		out[token] = stats
	}
	return out, rows.Err()
}
