package parser_test

import (
	"context"
	"os"
	"path/filepath"
	"testing"

	"bit.admedia.com/scm/ad/adpilot-indexing-code-parser.com/internal/service/parser"
	goparser "bit.admedia.com/scm/ad/adpilot-indexing-code-parser.com/internal/service/parser/go"
	"bit.admedia.com/scm/ad/adpilot-indexing-code-parser.com/internal/store"
)

func TestPipeline_ParsePersistPublish(t *testing.T) {
	workspace := setupWorkspace(t, map[string]string{
		"main.go": "package main\n\nfunc main() {}\n",
	})
	artifactDir := t.TempDir()

	fs, err := store.NewFilesystemStore(artifactDir)
	if err != nil {
		t.Fatalf("NewFilesystemStore: %v", err)
	}

	pub := &mockPublisher{}
	svc := parser.NewService(parser.ServiceConfig{
		WorkspacePath: workspace,
		Workers:       2,
		ParserVersion: "v0.1.0-test",
	}, []parser.LanguageAnalyzer{goparser.NewAnalyzer()}, pub, fs)

	event := fileChangedEvent("snap_pipeline", "main.go")
	if err := svc.ProcessFileChanged(context.Background(), event); err != nil {
		t.Fatalf("ProcessFileChanged: %v", err)
	}

	jobID := parser.JobIDFromEvent(event)
	job, ok := svc.GetParseJob(jobID)
	if !ok {
		t.Fatal("expected job")
	}
	if job.Status != parser.JobStatusCompleted {
		t.Fatalf("status: got %q, want completed", job.Status)
	}
	if job.ArtifactID == "" {
		t.Fatal("expected artifact_id on completed job")
	}

	artifactPath := filepath.Join(artifactDir, job.ArtifactID+".json")
	if _, err := os.Stat(artifactPath); err != nil {
		t.Fatalf("artifact file missing: %v", err)
	}

	metadata, err := fs.GetArtifactMetadata(context.Background(), job.ArtifactID)
	if err != nil {
		t.Fatalf("GetArtifactMetadata: %v", err)
	}
	if metadata.FilePath != "main.go" {
		t.Fatalf("file_path: got %q, want main.go", metadata.FilePath)
	}

	chunks, graphs, _, diags := pub.counts()
	if chunks != 1 || graphs != 0 {
		t.Fatalf("expected 1 chunks publish and no per-file graph, got chunks=%d graph=%d", chunks, graphs)
	}
	if diags != 0 {
		t.Fatalf("expected 0 diagnostics, got %d", diags)
	}
}
