package entity_test

import (
	"log"
	"os"
	"path/filepath"
	"reflect"
	"testing"
	"xyj-figures/pkg/entity"
	"xyj-figures/pkg/relationship"

	"github.com/go-test/deep"
)

func TestLoad(t *testing.T) {
	tmpDir := os.TempDir()
	tcs := []struct {
		name    string
		payload string
		want    entity.Entity
		wanterr bool
		err     error
	}{
		{
			name: "Valid Character",
			payload: `schema: v1
type: character
details:
  name: 孙悟空
  other_names:
  - 孙行者
  - 者行孙
  relationships:
  - source: 孙悟空
    destination: 唐三藏
    description: 师徒
    bidirection: true
  description: 孙悟空是明朝中后期畅销小说《西游记》当中个第一主角，是从石头里向蹦出来个猢狲。
  links:
  - https://zh.wikipedia.org/wiki/%E5%AD%99%E6%82%9F%E7%A9%BA
`,
			want: entity.Entity{
				Schema: "v1",
				Type:   entity.EntityTypeCharacter,
				Details: entity.Character{
					Name:       "孙悟空",
					OtherNames: []string{"孙行者", "者行孙"},
					Relationships: []relationship.Relationship{
						{
							Src:         "孙悟空",
							Dst:         "唐三藏",
							Description: "师徒",
							Bidirection: true,
						},
					},
					Description: "孙悟空是明朝中后期畅销小说《西游记》当中个第一主角，是从石头里向蹦出来个猢狲。",
					Links: []string{
						"https://zh.wikipedia.org/wiki/%E5%AD%99%E6%82%9F%E7%A9%BA",
					},
				},
			},
			wanterr: false,
		},
		{
			name: "Valid Group",
			payload: `schema: v1
type: group
details:
  name: 唐僧师徒
  other_names:
  - 取经团队
  members:
  - 孙悟空
  - 猪八戒
  - 沙僧
  - 唐僧
  - 白龙马
  links:
  - https://zh.wikipedia.org/wiki/%E8%A5%BF%E6%B8%B8%E8%AE%B0%E8%A7%92%E8%89%B2%E5%88%97%E8%A1%A8#%E5%94%90%E5%83%A7%E5%B8%AB%E5%BE%92
`,
			want: entity.Entity{
				Schema: "v1",
				Type:   entity.EntityTypeGroup,
				Details: entity.Group{
					Name:       "唐僧师徒",
					OtherNames: []string{"取经团队"},
					Members:    []string{"孙悟空", "猪八戒", "沙僧", "唐僧", "白龙马"},
					Links: []string{
						"https://zh.wikipedia.org/wiki/%E8%A5%BF%E6%B8%B8%E8%AE%B0%E8%A7%92%E8%89%B2%E5%88%97%E8%A1%A8#%E5%94%90%E5%83%A7%E5%B8%AB%E5%BE%92",
					},
				},
			},
			wanterr: false,
		},
	}
	for _, tc := range tcs {
		t.Run(tc.name, func(t *testing.T) {
			// Prepare data
			tmpFile, err := os.Create(filepath.Join(tmpDir, tc.name))
			if err != nil {
				t.Fatalf("Failed to create temporary file: %v", err)
			}
			defer tmpFile.Close()

			if _, err = tmpFile.Write([]byte(tc.payload)); err != nil {
				t.Fatalf("Failed to write to temporary file: %v", err)
			}

			// Call the function and assert the results
			e, err := entity.Load(tmpFile.Name())
			if err != nil && !tc.wanterr {
				t.Errorf("Unexpected error: %v", err)
			}
			if err == nil && tc.wanterr {
				t.Errorf("expected error but not get")
			}
			// Sanity Check
			if !reflect.DeepEqual(*e, tc.want) {
				log.Fatalf("Load got %+v want %+v, diff %+v", *e, tc.want, deep.Equal(*e, tc.want))
			}
		})
	}
}
