package store

import (
	"context"
	"testing"
	"time"

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

func TestPostgresPoolConfigSetsDiagnosticAndConnectTimeout(t *testing.T) {
	config, err := postgresPoolConfig("postgresql://gateway:password@localhost:5432/gateway?sslmode=disable")
	if err != nil {
		t.Fatalf("parse PostgreSQL pool config: %v", err)
	}
	if config.ConnConfig.ConnectTimeout != 5*time.Second {
		t.Fatalf("connect timeout = %s, want 5s", config.ConnConfig.ConnectTimeout)
	}
	if applicationName := config.ConnConfig.RuntimeParams["application_name"]; applicationName != "easyai-ai-gateway" {
		t.Fatalf("application_name = %q, want easyai-ai-gateway", applicationName)
	}
}

func TestPostgresPoolConfigRejectsMalformedURL(t *testing.T) {
	if _, err := postgresPoolConfig("://malformed"); err == nil {
		t.Fatal("expected malformed PostgreSQL URL to fail")
	}
}

func TestIsPostgresUnavailableClassifiesConnectivityFailures(t *testing.T) {
	for _, testCase := range []struct {
		name string
		err  error
	}{
		{name: "deadline", err: context.DeadlineExceeded},
		{name: "connection exception", err: &pgconn.PgError{Code: "08006"}},
		{name: "too many connections", err: &pgconn.PgError{Code: "53300"}},
		{name: "cannot connect now", err: &pgconn.PgError{Code: "57P03"}},
	} {
		t.Run(testCase.name, func(t *testing.T) {
			if !IsPostgresUnavailable(testCase.err) {
				t.Fatalf("error %v was not classified as PostgreSQL unavailable", testCase.err)
			}
		})
	}
	if IsPostgresUnavailable(&pgconn.PgError{Code: "42601"}) {
		t.Fatal("SQL syntax error was incorrectly classified as PostgreSQL unavailable")
	}
}
