package api

import (
	"encoding/json"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestChatID_IntForm(t *testing.T) {
	c := ChatIDFromInt(-1001234567890)
	require.False(t, c.IsZero())
	require.Equal(t, "-1001234567890", c.String())

	data, err := json.Marshal(c)
	require.NoError(t, err)
	require.Equal(t, "-1001234567890", string(data))

	var c2 ChatID
	require.NoError(t, json.Unmarshal(data, &c2))
	require.Equal(t, c, c2)
}

func TestChatID_UsernameForm(t *testing.T) {
	c := ChatIDFromUsername("@channel")
	require.False(t, c.IsZero())
	require.Equal(t, "@channel", c.String())

	data, err := json.Marshal(c)
	require.NoError(t, err)
	require.Equal(t, `"@channel"`, string(data))

	var c2 ChatID
	require.NoError(t, json.Unmarshal(data, &c2))
	require.Equal(t, c, c2)
}

func TestChatID_Zero(t *testing.T) {
	var c ChatID
	require.True(t, c.IsZero())
	require.Equal(t, "", c.String())

	data, err := json.Marshal(c)
	require.NoError(t, err)
	require.Equal(t, "null", string(data))

	var c2 ChatID
	require.NoError(t, json.Unmarshal([]byte("null"), &c2))
	require.True(t, c2.IsZero())
}

func TestChatID_UnmarshalInvalid(t *testing.T) {
	var c ChatID
	err := json.Unmarshal([]byte(`"not-a-number"`), &c)
	require.NoError(t, err) // string always succeeds as username
	require.Equal(t, "not-a-number", c.username)
}

func TestMessageOrBool_TrueForm(t *testing.T) {
	var m MessageOrBool
	require.NoError(t, json.Unmarshal([]byte("true"), &m))
	require.True(t, m.OK)
	require.Nil(t, m.Message)
}

func TestMessageOrBool_FalseForm(t *testing.T) {
	var m MessageOrBool
	require.NoError(t, json.Unmarshal([]byte("false"), &m))
	require.False(t, m.OK)
	require.Nil(t, m.Message)
}

func TestMessageOrBool_MessageForm(t *testing.T) {
	// Message is a generated type; we can only test that it unmarshals without
	// error into the struct — the generated api/*.gen.go is not available in
	// the test build unless built. Use build tag !ignore_autogenerated default.
	// Skip if Message type is not yet present (bootstrap phase).
	data := []byte(`{"message_id":42,"date":0,"chat":{"id":1,"type":"private"}}`)
	var m MessageOrBool
	require.NoError(t, json.Unmarshal(data, &m))
	require.NotNil(t, m.Message)
	require.False(t, m.OK)
}

func TestInputFile_IsLocalUpload(t *testing.T) {
	require.False(t, (*InputFile)(nil).IsLocalUpload())
	require.False(t, (&InputFile{PathOrID: "AgADAgADu7gxG..."}).IsLocalUpload())
	require.True(t, (&InputFile{Reader: nopReader{}}).IsLocalUpload())
}

type nopReader struct{}

func (nopReader) Read(p []byte) (int, error) { return 0, nil }
