package parser_test

import (
	"encoding/json"
	"testing"

	"git.max-richter.dev/max/marka/parser"
	"git.max-richter.dev/max/marka/testdata"
	"github.com/google/go-cmp/cmp"
)

func TestParse_DetectType(t *testing.T) {
	recipe := testdata.Read(t, "recipe_salad/input.md")
	article := testdata.Read(t, "article_simple/input.md")

	recipeType, err := parser.DetectType(string(recipe))
	if err != nil {
		t.Fatalf("failed to detect recipeType: %v", err)
	}

	articleType, err := parser.DetectType(string(article))
	if err != nil {
		t.Fatalf("failed to detect articleType: %v", err)
	}

	if recipeType != "Recipe" {
		t.Errorf("recipeType did not match expected type 'Recipe' -> %s", recipeType)
	}

	if articleType != "Article" {
		t.Errorf("articleType did not match expected type 'Article' -> %s", articleType)
	}
}

func TestParse_RecipeSalad(t *testing.T) {
	inputContent := testdata.Read(t, "recipe_salad/input.md")
	output := testdata.Read(t, "recipe_salad/output.json")

	got, err := parser.ParseFile(string(inputContent))
	if err != nil {
		t.Fatalf("ParseFile: %v", err)
	}

	var want map[string]any
	if err := json.Unmarshal(output, &want); err != nil {
		t.Fatalf("unmarshal expected.json: %v", err)
	}

	if diff := cmp.Diff(want, got); diff != "" {
		t.Fatalf("JSON mismatch (-want +got):\n%s", diff)
	}
}

func TestParse_RecipeNoDescription(t *testing.T) {
	inputContent := testdata.Read(t, "recipe_no_description/input.md")

	got, err := parser.ParseFile(string(inputContent))
	if err != nil {
		t.Fatalf("ParseFile: %v", err)
	}

	var want map[string]any
	output := testdata.Read(t, "recipe_no_description/output.json")
	if err := json.Unmarshal(output, &want); err != nil {
		t.Fatalf("unmarshal expected.json: %v", err)
	}

	if diff := cmp.Diff(want, got); diff != "" {
		t.Fatalf("JSON mismatch (-want +got):\n%s", diff)
	}
}

func TestParse_Baguette(t *testing.T) {
	inputContent := testdata.Read(t, "baguette/input.md")

	got, err := parser.ParseFile(string(inputContent))
	if err != nil {
		t.Fatalf("ParseFile: %v", err)
	}

	var want map[string]any
	output := testdata.Read(t, "baguette/output.json")
	if err := json.Unmarshal(output, &want); err != nil {
		t.Fatalf("unmarshal expected.json: %v", err)
	}

	if diff := cmp.Diff(want, got); diff != "" {
		t.Fatalf("JSON mismatch (-want +got):\n%s", diff)
	}
}

func TestParse_Article(t *testing.T) {
	inputContent := testdata.Read(t, "article_simple/input.md")

	got, err := parser.ParseFile(string(inputContent))
	if err != nil {
		t.Fatalf("ParseFile: %v", err)
	}

	var want map[string]any
	output := testdata.Read(t, "article_simple/output.json")
	if err := json.Unmarshal(output, &want); err != nil {
		t.Fatalf("unmarshal expected.json: %v", err)
	}

	if diff := cmp.Diff(want, got); diff != "" {
		t.Fatalf("JSON mismatch (-want +got):\n%s", diff)
	}
}
