package store

import (
	"errors"
	"testing"
)

func TestCreateAndGetApp(t *testing.T) {
	s := newTestStore(t)

	a, err := s.CreateApp(App{Name: "my-saas", Description: "All the things"})
	if err != nil {
		t.Fatalf("CreateApp: %v", err)
	}
	if a.ID == "" {
		t.Fatal("app ID should be set")
	}

	got, err := s.GetAppByID(a.ID)
	if err != nil {
		t.Fatalf("GetAppByID: %v", err)
	}
	if got.Name != "my-saas" {
		t.Fatalf("got name %q", got.Name)
	}
}

func TestUniqueAppName(t *testing.T) {
	s := newTestStore(t)

	if _, err := s.CreateApp(App{Name: "dupe"}); err != nil {
		t.Fatalf("first insert: %v", err)
	}
	if _, err := s.CreateApp(App{Name: "dupe"}); err == nil {
		t.Fatal("expected UNIQUE name violation, got nil")
	}
}

func TestListApps(t *testing.T) {
	s := newTestStore(t)

	s.CreateApp(App{Name: "bravo"})
	s.CreateApp(App{Name: "alpha"})

	out, err := s.ListApps()
	if err != nil {
		t.Fatalf("ListApps: %v", err)
	}
	if len(out) != 2 {
		t.Fatalf("expected 2 apps, got %d", len(out))
	}
	if out[0].Name != "alpha" {
		t.Fatalf("expected alpha first, got %q", out[0].Name)
	}
}

func TestDeleteAppClearsWorkloadAppID(t *testing.T) {
	s := newTestStore(t)

	app, _ := s.CreateApp(App{Name: "doomed"})
	w, _ := s.CreateWorkload(Workload{
		Kind: "project", RefID: "p1", Name: "n", AppID: app.ID,
	})

	if err := s.DeleteApp(app.ID); err != nil {
		t.Fatalf("DeleteApp: %v", err)
	}

	got, _ := s.GetWorkloadByID(w.ID)
	if got.AppID != "" {
		t.Fatalf("expected workload app_id cleared, got %q", got.AppID)
	}

	if _, err := s.GetAppByID(app.ID); !errors.Is(err, ErrNotFound) {
		t.Fatalf("expected app NotFound after delete, got %v", err)
	}
}
