//go:build windows

package main

import (
	"errors"
	"syscall"
	"testing"
)

func withMessageBoxW(t *testing.T, fn func(hwnd, text, caption, flags uintptr) (uintptr, error)) {
	t.Helper()

	old := callMessageBoxW
	callMessageBoxW = fn
	t.Cleanup(func() {
		callMessageBoxW = old
	})
}

func TestMessageBoxW_WindowsOnly_InvalidUTF16(t *testing.T) {
	err := messageBox("bad\x00title", "测试消息", mbIconInformation)
	if err == nil {
		t.Fatal("包含 NUL 字符时应该返回错误")
	}
}

func TestMessageBoxW_WindowsOnly_SuccessIgnoresLastError(t *testing.T) {
	withMessageBoxW(t, func(_, _, _, _ uintptr) (uintptr, error) {
		return 1, syscall.Errno(123)
	})

	if err := messageBox("测试标题", "测试消息", mbIconInformation); err != nil {
		t.Fatalf("MessageBoxW 返回成功时应忽略 last error: %v", err)
	}
}

func TestMessageBoxW_WindowsOnly_FailureUsesReturnValue(t *testing.T) {
	withMessageBoxW(t, func(_, _, _, _ uintptr) (uintptr, error) {
		return 0, syscall.Errno(5)
	})

	err := messageBox("测试标题", "测试消息", mbIconInformation)
	if !errors.Is(err, syscall.Errno(5)) {
		t.Fatalf("MessageBoxW 返回 0 时应返回调用错误: %v", err)
	}
}

func TestShowError_WindowsBranch(t *testing.T) {
	withMessageBoxW(t, func(_, _, _, _ uintptr) (uintptr, error) {
		return 0, syscall.Errno(5)
	})

	defer func() {
		if recovered := recover(); recovered != nil {
			t.Fatalf("showError 不应因 MessageBoxW 失败而 panic: %v", recovered)
		}
	}()

	showError("测试错误", "这是一条测试错误消息")
}
