// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package goal_test

import (
	"context"
	"errors"
	"testing"
	"time"

	"git.secluded.site/np/internal/goal"
	"git.secluded.site/np/internal/testutil"
	"git.secluded.site/np/internal/timeutil"
)

func TestStoreSetAndGet(t *testing.T) {
	ctx := context.Background()
	db := testutil.OpenDB(t)

	fixed := time.Date(2025, time.January, 12, 8, 30, 0, 0, time.FixedZone("TEST", 2*3600))
	store := goal.NewStore(db, timeutil.FixedClock{Time: fixed})

	doc, err := store.Set(ctx, "sid-1", "  My Goal  ", "describe")
	if err != nil {
		t.Fatalf("Set: %v", err)
	}

	if want, got := "My Goal", doc.Title; want != got {
		t.Fatalf("Title mismatch: want %q got %q", want, got)
	}
	if want, got := "describe", doc.Description; want != got {
		t.Fatalf("Description mismatch: want %q got %q", want, got)
	}
	if want, got := fixed.UTC(), doc.UpdatedAt; !want.Equal(got) {
		t.Fatalf("UpdatedAt mismatch: want %v got %v", want, got)
	}

	loaded, err := store.Get(ctx, "sid-1")
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	if loaded != doc {
		t.Fatalf("Loaded doc mismatch: want %+v got %+v", doc, loaded)
	}

	exists, err := store.Exists(ctx, "sid-1")
	if err != nil {
		t.Fatalf("Exists: %v", err)
	}
	if !exists {
		t.Fatalf("Exists returned false")
	}

	exists, err = store.Exists(ctx, "sid-unknown")
	if err != nil {
		t.Fatalf("Exists unknown: %v", err)
	}
	if exists {
		t.Fatalf("Exists should be false for unknown session")
	}
}

func TestStoreGetMissing(t *testing.T) {
	ctx := context.Background()
	db := testutil.OpenDB(t)
	store := goal.NewStore(db, timeutil.FixedClock{Time: time.Now()})

	_, err := store.Get(ctx, "missing")
	if !errors.Is(err, goal.ErrNotFound) {
		t.Fatalf("expected ErrNotFound, got %v", err)
	}
}

func TestStoreSetRequiresTitle(t *testing.T) {
	ctx := context.Background()
	db := testutil.OpenDB(t)
	store := goal.NewStore(db, timeutil.FixedClock{Time: time.Now()})

	if _, err := store.Set(ctx, "sid", "   ", "desc"); !errors.Is(err, goal.ErrEmptyTitle) {
		t.Fatalf("expected ErrEmptyTitle, got %v", err)
	}
}
