package services

import (
	"bytes"
	"context"
	"encoding/binary"
	"errors"
	"image"
	"image/color"
	"image/png"
	"os"
	"strings"
	"testing"

	mp4 "github.com/abema/go-mp4"
	"go.mau.fi/whatsmeow"
	waProto "go.mau.fi/whatsmeow/proto/waE2E"
	"go.mau.fi/whatsmeow/types"
)

func statusPNG(t *testing.T) []byte {
	t.Helper()
	img := image.NewRGBA(image.Rect(0, 0, 80, 60))
	img.Set(0, 0, color.RGBA{R: 128, G: 230, B: 180, A: 255})
	var b bytes.Buffer
	if err := png.Encode(&b, img); err != nil {
		t.Fatal(err)
	}
	return b.Bytes()
}
func statusVideo(t *testing.T) []byte {
	t.Helper()
	data, err := os.ReadFile("testdata/status/video.mp4")
	if err != nil {
		t.Fatal(err)
	}
	return data
}

type fakeStatusClient struct {
	mediaKind          whatsmeow.MediaType
	message            *waProto.Message
	target             types.JID
	uploadErr, sendErr error
	uploads, sends     int
}

func (*fakeStatusClient) IsConnected() bool { return true }
func (f *fakeStatusClient) Upload(_ context.Context, data []byte, kind whatsmeow.MediaType) (whatsmeow.UploadResponse, error) {
	f.mediaKind = kind
	f.uploads++
	return whatsmeow.UploadResponse{URL: "https://fixture.invalid/media", DirectPath: "/fixture", FileLength: uint64(len(data))}, f.uploadErr
}
func (f *fakeStatusClient) SendMessage(_ context.Context, to types.JID, msg *waProto.Message, _ ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error) {
	f.target, f.message = to, msg
	f.sends++
	return whatsmeow.SendResponse{}, f.sendErr
}

func TestStatusPayloadTextImageVideoAndCaptionLinks(t *testing.T) {
	caption := "Promo spesial 👋\n\nhttps://example.com/beli?paket=a&ref=wa#harga"
	for _, tc := range []struct {
		name, mime string
		data       []byte
		kind       whatsmeow.MediaType
	}{
		{name: "text"}, {name: "image", mime: "image/png", data: statusPNG(t), kind: whatsmeow.MediaImage},
		{name: "video", mime: "video/mp4", data: statusVideo(t), kind: whatsmeow.MediaVideo},
	} {
		t.Run(tc.name, func(t *testing.T) {
			client := &fakeStatusClient{}
			if err := postStatusWithClient(context.Background(), client, caption, tc.mime, tc.data); err != nil {
				t.Fatal(err)
			}
			if client.sends != 1 || client.target != types.StatusBroadcastJID {
				t.Fatalf("wrong send target/count: %+v", client)
			}
			switch tc.name {
			case "text":
				m := client.message.GetExtendedTextMessage()
				if client.uploads != 0 || m.GetText() != caption || m.GetMatchedText() != "https://example.com/beli?paket=a&ref=wa#harga" || m.GetBackgroundArgb() != 0xFF128C7E {
					t.Fatalf("text/link changed: %v", m)
				}
			case "image":
				m := client.message.GetImageMessage()
				if m.GetCaption() != caption || m.GetWidth() != 80 || len(m.GetJPEGThumbnail()) == 0 || client.mediaKind != tc.kind {
					t.Fatalf("invalid image payload: %v", m)
				}
			case "video":
				m := client.message.GetVideoMessage()
				if m.GetCaption() != caption || m.GetSeconds() == 0 || m.GetSeconds() > 2 || m.GetWidth() != 160 || client.mediaKind != tc.kind {
					t.Fatalf("invalid video payload: %v", m)
				}
			}
		})
	}
}

func TestStatusRejectsInvalidOrOversizedMedia(t *testing.T) {
	video := statusVideo(t)
	long := append([]byte(nil), video...)
	_, err := mp4.ReadBoxStructure(bytes.NewReader(video), func(h *mp4.ReadHandle) (interface{}, error) {
		if h.BoxInfo.Type == mp4.BoxTypeMoov() {
			return h.Expand()
		}
		if h.BoxInfo.Type == mp4.BoxTypeMvhd() {
			box, _, err := h.ReadPayload()
			if err != nil {
				return nil, err
			}
			mvhd := box.(*mp4.Mvhd)
			offset := h.BoxInfo.Offset + h.BoxInfo.HeaderSize + 16
			binary.BigEndian.PutUint32(long[offset:offset+4], mvhd.Timescale*91)
		}
		return nil, nil
	})
	if err != nil {
		t.Fatal(err)
	}
	for name, data := range map[string][]byte{
		"empty": nil, "html": []byte("<html>not an image</html>"), "truncated": video[:64],
		"too-large": make([]byte, StatusVideoMaxBytes+1), "over-90-seconds": long,
		"unsupported-video-codec": bytes.ReplaceAll(video, []byte("avc1"), []byte("hvc1")),
		"unsupported-audio-codec": bytes.ReplaceAll(video, []byte("mp4a"), []byte("Opus")),
	} {
		t.Run(name, func(t *testing.T) {
			if _, err := InspectStatusMedia(data); err == nil {
				t.Fatal("invalid media accepted")
			}
		})
	}
}

func TestStatusFailureDoesNotTurnMediaIntoTextOrRetryUncertainSends(t *testing.T) {
	for _, tc := range []struct {
		name, text, mime   string
		data               []byte
		uploadErr, sendErr error
		uncertain          bool
	}{
		{name: "missing-media", text: "caption", mime: "image/png"},
		{name: "wrong-mime", text: "caption", mime: "video/mp4", data: statusPNG(t)},
		{name: "long-text", text: strings.Repeat("a", StatusTextMaxChars+1)},
		{name: "upload-error", text: "caption", mime: "image/png", data: statusPNG(t), uploadErr: errors.New("fixture upload")},
		{name: "send-error", text: "https://example.com", sendErr: context.DeadlineExceeded, uncertain: true},
	} {
		t.Run(tc.name, func(t *testing.T) {
			client := &fakeStatusClient{uploadErr: tc.uploadErr, sendErr: tc.sendErr}
			err := postStatusWithClient(context.Background(), client, tc.text, tc.mime, tc.data)
			if err == nil {
				t.Fatal("expected failure")
			}
			var uncertain *StatusSendUncertainError
			if errors.As(err, &uncertain) != tc.uncertain {
				t.Fatalf("wrong error classification: %v", err)
			}
			wantSends := 0
			if tc.uncertain {
				wantSends = 1
			}
			if client.sends != wantSends {
				t.Fatalf("unexpected send or retry: %d", client.sends)
			}
		})
	}
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	client := &fakeStatusClient{}
	if err := postStatusWithClient(ctx, client, "hello", "", nil); err == nil || client.sends != 0 {
		t.Fatal("cancelled context sent")
	}
}
