package stacks

import (
	"io"
	"log"
	"path/filepath"
	"testing"

	"gitea.dooplex.hu/admin/felhom-controller/internal/appbackup"
)

func dpBinds() []appbackup.ComposeBind {
	return []appbackup.ComposeBind{
		{Root: appbackup.RootImport, RelPath: "paperless"},
		{Root: appbackup.RootUserdata, RelPath: "media/books"},
		{Root: appbackup.RootHDD, RelPath: "appdata/paperless/media"},
	}
}

func quietLogger() *log.Logger { return log.New(io.Discard, "", 0) }

// Fork-3 ruling, half 1: a MALFORMED PATH is a WHOLE-BLOCK reject. Paths govern data handling.
func TestDataPaths_MalformedPathWholeBlockRejects(t *testing.T) {
	for _, tc := range []struct {
		name  string
		entry DataPath
	}{
		{"absolute", DataPath{Path: "/etc/passwd", Root: appbackup.RootImport, Role: RoleImport, Label: "x"}},
		{"traversal", DataPath{Path: "../../etc", Root: appbackup.RootImport, Role: RoleImport, Label: "x"}},
		{"backslash", DataPath{Path: `a\b`, Root: appbackup.RootImport, Role: RoleImport, Label: "x"}},
		{"non-clean", DataPath{Path: "a//b", Root: appbackup.RootImport, Role: RoleImport, Label: "x"}},
		{"empty", DataPath{Path: "", Root: appbackup.RootImport, Role: RoleImport, Label: "x"}},
		{"matches no compose bind", DataPath{Path: "nincs-ilyen", Root: appbackup.RootImport, Role: RoleImport, Label: "x"}},
		{"unknown root", DataPath{Path: "paperless", Root: appbackup.BindRoot("bogus"), Role: RoleImport, Label: "x"}},
	} {
		// A VALID entry sits alongside it — the reject must take the whole block, not just the bad one.
		entries := []DataPath{
			{Path: "media/books", Root: appbackup.RootUserdata, Role: RoleLibrary, Label: "ok"},
			tc.entry,
		}
		kept, err := ValidateDataPaths(entries, dpBinds(), "test-app", quietLogger())
		if err == nil {
			t.Errorf("%s: must be rejected, got kept=%v", tc.name, kept)
		}
		if kept != nil {
			t.Errorf("%s: a whole-block reject must keep NOTHING, got %v", tc.name, kept)
		}
	}
}

// Fork-3 ruling, half 2: an UNKNOWN ROLE fails OPEN. Roles govern presentation only, so a typo in a
// catalog push must never brick the template (the Lifecycle precedent).
func TestDataPaths_UnknownRoleFailsOpen(t *testing.T) {
	entries := []DataPath{
		{Path: "paperless", Root: appbackup.RootImport, Role: DataPathRole("beolvasas"), Label: "typo role"},
		{Path: "media/books", Root: appbackup.RootUserdata, Role: RoleLibrary, Label: "E-könyvtár"},
	}
	kept, err := ValidateDataPaths(entries, dpBinds(), "test-app", quietLogger())
	if err != nil {
		t.Fatalf("an unknown ROLE must not reject the block: %v", err)
	}
	if len(kept) != 1 || kept[0].Path != "media/books" {
		t.Errorf("expected only the valid entry to survive, got %v", kept)
	}
}

// The happy path across all three roots and roles.
func TestDataPaths_AllRootsAndRoles(t *testing.T) {
	entries := []DataPath{
		{Path: "paperless", Root: appbackup.RootImport, Role: RoleImport, Label: "Beolvasandó dokumentumok"},
		{Path: "media/books", Root: appbackup.RootUserdata, Role: RoleLibrary, Label: "E-könyvtár"},
		{Path: "appdata/paperless/media", Root: appbackup.RootHDD, Role: RoleExport, Label: "Export"},
	}
	kept, err := ValidateDataPaths(entries, dpBinds(), "test-app", quietLogger())
	if err != nil {
		t.Fatalf("valid block rejected: %v", err)
	}
	if len(kept) != 3 {
		t.Errorf("expected all 3 entries kept, got %d: %v", len(kept), kept)
	}
}

func TestDataPaths_DuplicateRejects(t *testing.T) {
	entries := []DataPath{
		{Path: "paperless", Root: appbackup.RootImport, Role: RoleImport, Label: "a"},
		{Path: "paperless", Root: appbackup.RootImport, Role: RoleImport, Label: "b"},
	}
	if _, err := ValidateDataPaths(entries, dpBinds(), "test-app", quietLogger()); err == nil {
		t.Error("a duplicate (root, path) must be rejected")
	}
}

// data_paths ANNOTATES; it must never be able to declare a path that is not already a compose bind.
// This is the property that keeps the design from introducing a new filesystem-write primitive.
func TestDataPaths_CannotDeclareNewPaths(t *testing.T) {
	entries := []DataPath{
		{Path: "uj-mappa", Root: appbackup.RootUserdata, Role: RoleLibrary, Label: "new"},
	}
	_, err := ValidateDataPaths(entries, dpBinds(), "test-app", quietLogger())
	if err == nil {
		t.Fatal("data_paths must not be able to name a path with no compose bind behind it")
	}
}

// End-to-end through LoadMetadata: the catalog shape parses, validates, and survives.
func TestLoadMetadata_DataPathsRoundTrip(t *testing.T) {
	compose := `services:
  calibre-web:
    image: x
    volumes:
      - ${IMPORT_PATH}/calibre:/cwa-book-ingest
      - ${USERDATA_PATH}/media/books:/calibre-library
`
	meta := `display_name: Calibre-Web
slug: calibre-web
backup:
  userdata:
    - path: media/books
      class: mandatory
  import:
    - path: calibre
      class: excluded
data_paths:
  - path: calibre
    root: import
    role: import
    label: "Beolvasandó e-könyvek"
  - path: media/books
    root: userdata
    role: library
    label: "E-könyvtár"
`
	dir := writeApp(t, compose, meta)
	m := LoadMetadata(dir)
	if len(m.DataPaths) != 2 {
		t.Fatalf("expected 2 data_paths, got %d: %+v", len(m.DataPaths), m.DataPaths)
	}
	if m.Backup == nil {
		t.Error("the backup block must survive alongside data_paths")
	}
	if m.DataPaths[0].Label != "Beolvasandó e-könyvek" || m.DataPaths[0].Role != RoleImport {
		t.Errorf("first entry wrong: %+v", m.DataPaths[0])
	}
	_ = filepath.Clean
}

// A bad data_paths block must NOT take the backup block down with it — they are validated
// independently at the same choke point.
func TestLoadMetadata_BadDataPathsKeepsBackupBlock(t *testing.T) {
	compose := `services:
  app:
    image: x
    volumes:
      - ${USERDATA_PATH}/media/books:/lib
`
	meta := `display_name: X
slug: x
backup:
  userdata:
    - path: media/books
      class: mandatory
data_paths:
  - path: /absolute/nope
    root: userdata
    role: library
    label: "bad"
`
	dir := writeApp(t, compose, meta)
	m := LoadMetadata(dir)
	if m.DataPaths != nil {
		t.Errorf("malformed data_paths must be dropped, got %+v", m.DataPaths)
	}
	if m.Backup == nil {
		t.Error("a bad data_paths block must not reject the backup block — they are independent")
	}
}
