package qcclient

import (
	"encoding/json"
	"testing"
)

func TestBoolish_UnmarshalJSON(t *testing.T) {
	tests := []struct {
		name      string
		input     string
		want      bool
		expectErr bool
	}{
		{name: "bool true", input: `true`, want: true},
		{name: "bool false", input: `false`, want: false},
		{name: "number one", input: `1`, want: true},
		{name: "number zero", input: `0`, want: false},
		{name: "number float", input: `2.5`, want: true},
		{name: "string one", input: `"1"`, want: true},
		{name: "string zero", input: `"0"`, want: false},
		{name: "string true", input: `"true"`, want: true},
		{name: "string false", input: `"false"`, want: false},
		{name: "string yes", input: `"yes"`, want: true},
		{name: "string no", input: `"no"`, want: false},
		{name: "string numeric", input: `"0.0"`, want: false},
		{name: "null", input: `null`, want: false},
		{name: "invalid string", input: `"maybe"`, expectErr: true},
		{name: "invalid object", input: `{}`, expectErr: true},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			var got Boolish
			err := json.Unmarshal([]byte(tc.input), &got)
			if tc.expectErr {
				if err == nil {
					t.Fatalf("expected error for input %s", tc.input)
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error for input %s: %v", tc.input, err)
			}
			if got.Bool() != tc.want {
				t.Fatalf("got %v, want %v for input %s", got.Bool(), tc.want, tc.input)
			}
		})
	}
}

func TestTemplateUnmarshal_PaletteReadyVariants(t *testing.T) {
	payload := `{
		"status":"ok",
		"data":[
			{"id":1,"name":"a","description":"","locale":"en","thumbnailUrl":"","templatePreviewUrl":"","type":"ai","paletteReady":true,"globalColors":{},"textsWithGlobalColors":{}},
			{"id":2,"name":"b","description":"","locale":"en","thumbnailUrl":"","templatePreviewUrl":"","type":"ai","paletteReady":1,"globalColors":{},"textsWithGlobalColors":{}},
			{"id":3,"name":"c","description":"","locale":"en","thumbnailUrl":"","templatePreviewUrl":"","type":"ai","paletteReady":"0","globalColors":{},"textsWithGlobalColors":{}}
		]
	}`

	var rsp APIResponse[[]Template]
	if err := json.Unmarshal([]byte(payload), &rsp); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	if len(rsp.Data) != 3 {
		t.Fatalf("unexpected template count: got %d, want 3", len(rsp.Data))
	}
	if !rsp.Data[0].PaletteReady.Bool() {
		t.Fatalf("template 1 paletteReady should be true")
	}
	if !rsp.Data[1].PaletteReady.Bool() {
		t.Fatalf("template 2 paletteReady should be true")
	}
	if rsp.Data[2].PaletteReady.Bool() {
		t.Fatalf("template 3 paletteReady should be false")
	}
}
