package api

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"

	"github.com/go-chi/chi/v5"
)

// newMeSystemPlaylistsRouter mounts only the route under test. Mirrors the
// per-handler routers in admin_covers_test.go.
func newMeSystemPlaylistsRouter(h *handlers) chi.Router {
	r := chi.NewRouter()
	r.Get("/api/me/system-playlists-status", h.handleGetSystemPlaylistsStatus)
	return r
}

func TestMeSystemPlaylistsStatus_NoSession401(t *testing.T) {
	h, _ := testHandlers(t)
	req := httptest.NewRequest(http.MethodGet, "/api/me/system-playlists-status", nil)
	rec := httptest.NewRecorder()
	newMeSystemPlaylistsRouter(h).ServeHTTP(rec, req)
	if rec.Code != http.StatusUnauthorized {
		t.Errorf("status = %d, want 401", rec.Code)
	}
}

func TestMeSystemPlaylistsStatus_NoRowReturnsDefault(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	user := seedUser(t, pool, "alice", "pw", false)
	req := httptest.NewRequest(http.MethodGet, "/api/me/system-playlists-status", nil)
	req = withUser(req, user)
	rec := httptest.NewRecorder()
	newMeSystemPlaylistsRouter(h).ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	var resp systemPlaylistsStatusResp
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if resp.InFlight {
		t.Errorf("in_flight = true, want false")
	}
	if resp.LastRunAt != nil {
		t.Errorf("last_run_at = %v, want nil", resp.LastRunAt)
	}
	if resp.LastError != nil {
		t.Errorf("last_error = %v, want nil", resp.LastError)
	}
}

func TestMeSystemPlaylistsStatus_RowReturnsValues(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	user := seedUser(t, pool, "bob", "pw", false)
	errMsg := "fetch failed"
	if _, err := pool.Exec(context.Background(), `
		INSERT INTO system_playlist_runs (user_id, in_flight, last_error)
		VALUES ($1, true, $2)
	`, user.ID, errMsg); err != nil {
		t.Fatalf("seed runs: %v", err)
	}

	req := httptest.NewRequest(http.MethodGet, "/api/me/system-playlists-status", nil)
	req = withUser(req, user)
	rec := httptest.NewRecorder()
	newMeSystemPlaylistsRouter(h).ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	var resp systemPlaylistsStatusResp
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if !resp.InFlight {
		t.Errorf("in_flight = false, want true")
	}
	if resp.LastError == nil || *resp.LastError != errMsg {
		t.Errorf("last_error = %v, want %q", resp.LastError, errMsg)
	}
}
