package database

import (
	"context"
	"os"
	"testing"
	"time"
)

func TestSQLiteDB(t *testing.T) {
	// Create temp database for testing
	tmpDB := "test.db"
	db, err := NewSQLiteDB(tmpDB)
	if err != nil {
		t.Fatalf("Failed to create test database: %v", err)
	}
	defer os.Remove(tmpDB)

	ctx := context.Background()
	if err := db.Init(ctx); err != nil {
		t.Fatalf("Failed to initialize database: %v", err)
	}

	t.Run("AddTask", func(t *testing.T) {
		id, err := db.AddTask(ctx, "Test task")
		if err != nil {
			t.Errorf("Failed to add task: %v", err)
		}
		if id <= 0 {
			t.Error("Expected positive task ID")
		}
	})

	t.Run("GetTasks", func(t *testing.T) {
		tasks, err := db.GetTasks(ctx, false)
		if err != nil {
			t.Errorf("Failed to get tasks: %v", err)
		}
		if len(tasks) == 0 {
			t.Error("Expected at least one task")
		}
	})

	t.Run("CompleteTask", func(t *testing.T) {
		// Add a task first
		id, _ := db.AddTask(ctx, "Task to complete")

		// Complete it
		err := db.CompleteTask(ctx, int(id))
		if err != nil {
			t.Errorf("Failed to complete task: %v", err)
		}

		// Verify it's in completed tasks
		tasks, _ := db.GetTasks(ctx, true)
		found := false
		for _, task := range tasks {
			if task.ID == id {
				found = true
				if !task.Completed {
					t.Error("Task should be marked as completed")
				}
				break
			}
		}
		if !found {
			t.Error("Completed task not found")
		}
	})

	t.Run("TaskAnalysis", func(t *testing.T) {
		// Add a task
		id, _ := db.AddTask(ctx, "Task for analysis")

		// Store analysis
		analysis := &Analysis{
			TaskID:     id,
			Result:     `{"priority":3,"category":"test"}`,
			AnalyzedAt: time.Now(),
		}

		err := db.StoreAnalysis(ctx, analysis)
		if err != nil {
			t.Errorf("Failed to store analysis: %v", err)
		}

		// Retrieve analysis
		retrieved, err := db.GetTaskAnalysis(ctx, int(id))
		if err != nil {
			t.Errorf("Failed to get analysis: %v", err)
		}
		if retrieved == nil {
			t.Error("Expected to retrieve analysis")
		}
		if retrieved.Result != analysis.Result {
			t.Errorf("Expected result %s, got %s", analysis.Result, retrieved.Result)
		}
	})
}
