package cmd

import (
	"bytes"
	"encoding/json"
	"strings"
	"testing"
)

func TestLanguagesJSONFormat(t *testing.T) {
	prev := languagesFormat
	defer func() { languagesFormat = prev }()
	languagesFormat = "json"

	var buf bytes.Buffer
	languagesCmd.SetOut(&buf)

	if err := runLanguages(languagesCmd, nil); err != nil {
		t.Fatalf("runLanguages returned error: %v", err)
	}

	var payload struct {
		Count     int `json:"count"`
		Languages []struct {
			Canonical string   `json:"canonical"`
			Aliases   []string `json:"aliases"`
		} `json:"languages"`
	}
	if err := json.Unmarshal(buf.Bytes(), &payload); err != nil {
		t.Fatalf("invalid json output: %v", err)
	}
	if payload.Count == 0 || len(payload.Languages) == 0 {
		t.Fatalf("expected non-empty languages payload, got %+v", payload)
	}

	foundNext := false
	for _, l := range payload.Languages {
		if l.Canonical == "nextjs" {
			foundNext = true
			break
		}
	}
	if !foundNext {
		t.Fatalf("expected nextjs in JSON payload, got %+v", payload.Languages)
	}
}

func TestLanguagesTextFormat(t *testing.T) {
	prev := languagesFormat
	defer func() { languagesFormat = prev }()
	languagesFormat = "text"

	var buf bytes.Buffer
	languagesCmd.SetOut(&buf)

	if err := runLanguages(languagesCmd, nil); err != nil {
		t.Fatalf("runLanguages returned error: %v", err)
	}
	out := buf.String()
	if !strings.Contains(out, "Devour Supported Languages") {
		t.Fatalf("unexpected text output: %q", out)
	}
}
