package handlers

import (
	"testing"

	"bookhoard/internal/database"

	"github.com/jackc/pgx/v5/pgtype"
	"github.com/stretchr/testify/assert"
)

func TestCompareValues_Equals(t *testing.T) {
	handler := &CollectionHandler{}

	result := handler.compareValues("Science Fiction", "equals", "Science Fiction")
	assert.True(t, result)

	result = handler.compareValues("Science Fiction", "equals", "Fantasy")
	assert.False(t, result)
}

func TestCompareValues_Contains(t *testing.T) {
	handler := &CollectionHandler{}

	result := handler.compareValues("Isaac Asimov", "contains", "asimov")
	assert.True(t, result)

	result = handler.compareValues("Isaac Asimov", "contains", "clarke")
	assert.False(t, result)
}

func TestCompareValues_GreaterThan(t *testing.T) {
	handler := &CollectionHandler{}

	result := handler.compareValues("2021", "greater_than", "2000")
	assert.True(t, result)

	result = handler.compareValues("1999", "greater_than", "2000")
	assert.False(t, result)
}

func TestCompareValues_NotEquals(t *testing.T) {
	handler := &CollectionHandler{}

	result := handler.compareValues("Science Fiction", "not_equals", "Fantasy")
	assert.True(t, result)

	result = handler.compareValues("Science Fiction", "not_equals", "Science Fiction")
	assert.False(t, result)
}

func TestEvaluateRule_Genre(t *testing.T) {
	item := database.ListMediaItemsRow{
		Genre: pgtype.Text{String: "Science Fiction", Valid: true},
	}

	handler := &CollectionHandler{}

	result := handler.evaluateRule(item, "genre", "equals", "Science Fiction")
	assert.True(t, result)

	result = handler.evaluateRule(item, "genre", "equals", "Fantasy")
	assert.False(t, result)
}

func TestEvaluateRule_Author(t *testing.T) {
	item := database.ListMediaItemsRow{
		Author: pgtype.Text{String: "Isaac Asimov", Valid: true},
	}

	handler := &CollectionHandler{}

	result := handler.evaluateRule(item, "author", "contains", "asimov")
	assert.True(t, result)

	result = handler.evaluateRule(item, "author", "contains", "clarke")
	assert.False(t, result)
}

func TestEvaluateRule_CopyrightYear(t *testing.T) {
	item := database.ListMediaItemsRow{
		CopyrightYear: pgtype.Int4{Int32: 2021, Valid: true},
	}

	handler := &CollectionHandler{}

	result := handler.evaluateRule(item, "copyright_year", "greater_than", "2000")
	assert.True(t, result)

	result = handler.evaluateRule(item, "copyright_year", "less_than", "2000")
	assert.False(t, result)
}

func TestTextToString(t *testing.T) {
	tests := []struct {
		name     string
		input    pgtype.Text
		expected string
	}{
		{"valid text", pgtype.Text{String: "hello", Valid: true}, "hello"},
		{"null text", pgtype.Text{Valid: false}, ""},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := textToString(tt.input)
			assert.Equal(t, tt.expected, result)
		})
	}
}
