package rosa_test

import (
	"errors"
	"os"
	"path/filepath"
	"syscall"
	"testing"
	"unique"

	"hakurei.app/internal/pkg"
	"hakurei.app/internal/rosa"
)

func TestReportZeroLength(t *testing.T) {
	report := filepath.Join(t.TempDir(), "report")
	if err := os.WriteFile(report, nil, 0400); err != nil {
		t.Fatal(err)
	}

	if _, err := rosa.OpenReport(report); !errors.Is(err, syscall.EINVAL) {
		t.Fatalf("OpenReport: error = %v", err)
	}
}

func TestReportSIGSEGV(t *testing.T) {
	report := filepath.Join(t.TempDir(), "report")
	if err := os.WriteFile(report, make([]byte, 64), 0400); err != nil {
		t.Fatal(err)
	}

	if r, err := rosa.OpenReport(report); err != nil {
		t.Fatalf("OpenReport: error = %v", err)
	} else {
		status, n := r.ArtifactOf(unique.Make(pkg.ID{}))
		if len(status) != 0 {
			t.Errorf("ArtifactsOf: status = %#v", status)
		}
		if n != 0 {
			t.Errorf("ArtifactsOf: n = %d", n)
		}

		if err = r.Close(); err != nil {
			t.Fatalf("Close: error = %v", err)
		}

		defer func() {
			ioErr := err.(*rosa.ReportIOError)
			if ioErr.Offset != 48 {
				panic(ioErr)
			}
		}()
		defer r.HandleAccess(&err)()
		for {
			r.ArtifactOf(unique.Make(pkg.ID{}))
		}
	}
}
