//go:build windows

package proc

import (
	"os"
	"os/exec"
	"testing"
	"time"

	"golang.org/x/sys/windows"
)

func TestFiletimeToTimeAndProcessIdentityComparison(t *testing.T) {
	filetime := windows.Filetime{
		LowDateTime:  3579702919,
		HighDateTime: 31267688,
	}
	got := filetimeToTime(filetime)
	want := time.Date(2026, 7, 24, 12, 34, 56, 123456700, time.UTC)
	if !got.Equal(want) {
		t.Fatalf("filetimeToTime = %v, want %v", got, want)
	}

	if !ProcessIdentityMatches(
		ProcessInfo{PID: 42, StartedAt: got},
		ProcessInfo{PID: 42, StartedAt: want},
	) {
		t.Fatal("exact FILETIME process identities did not match")
	}
	if ProcessIdentityMatches(
		ProcessInfo{PID: 42, StartedAt: got},
		ProcessInfo{PID: 42, StartedAt: want.Add(100 * time.Nanosecond)},
	) {
		t.Fatal("different FILETIME process identities matched")
	}
}

func TestProcessByPID(t *testing.T) {
	handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(os.Getpid()))
	if err != nil {
		t.Fatalf("OpenProcess: %v", err)
	}
	defer windows.CloseHandle(handle)

	startedAt, err := ProcessStartedAt(handle)
	if err != nil {
		t.Fatalf("ProcessStartedAt: %v", err)
	}
	process, ok := ProcessByPID(os.Getpid())
	if !ok {
		t.Fatal("ProcessByPID did not find the current process")
	}
	if process.PID != os.Getpid() {
		t.Fatalf("PID = %d, want %d", process.PID, os.Getpid())
	}
	if process.StartedAt.IsZero() {
		t.Fatal("StartedAt is zero")
	}
	if !process.StartedAt.Equal(startedAt) {
		t.Fatalf("ProcessByPID StartedAt = %v, ProcessStartedAt = %v", process.StartedAt, startedAt)
	}
}

func TestPIDAliveUsesNativeProcessState(t *testing.T) {
	if !PIDAlive(os.Getpid()) {
		t.Fatal("PIDAlive reported the current process as dead")
	}

	command := exec.Command("cmd.exe", "/c", "exit", "0")
	if err := command.Start(); err != nil {
		t.Fatalf("start short-lived process: %v", err)
	}
	pid := command.Process.Pid
	if err := command.Wait(); err != nil {
		t.Fatalf("wait for short-lived process: %v", err)
	}
	if PIDAlive(pid) {
		t.Fatalf("PIDAlive reported exited process %d as alive", pid)
	}
}
