package platform

import (
	"context"
	"os"
	"path/filepath"
	"testing"
	"time"
)

type blockDeviceInfo struct{ name string }

func (i blockDeviceInfo) Name() string     { return i.name }
func (blockDeviceInfo) Size() int64        { return 0 }
func (blockDeviceInfo) Mode() os.FileMode  { return os.ModeDevice }
func (blockDeviceInfo) ModTime() time.Time { return time.Time{} }
func (blockDeviceInfo) IsDir() bool        { return false }
func (blockDeviceInfo) Sys() any           { return nil }

func TestUnraidServiceEnabled(t *testing.T) {
	path := filepath.Join(t.TempDir(), "domain.cfg")
	for _, test := range []struct {
		content string
		want    bool
	}{
		{content: "SERVICE=\"enable\"\n", want: true},
		{content: "SERVICE=disable\n", want: false},
		{content: "OTHER=value\n", want: false},
	} {
		if err := os.WriteFile(path, []byte(test.content), 0600); err != nil {
			t.Fatal(err)
		}
		if got := unraidServiceEnabled(path); got != test.want {
			t.Fatalf("content %q: got %v, want %v", test.content, got, test.want)
		}
	}
}

func TestFlashDeviceResolvesWholeDiskBehindBootPartition(t *testing.T) {
	dir := t.TempDir()
	findmnt := filepath.Join(dir, "findmnt")
	lsblk := filepath.Join(dir, "lsblk")
	if err := os.WriteFile(findmnt, []byte("#!/bin/sh\nprintf '/dev/sda1\\n'\n"), 0700); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(lsblk, []byte("#!/bin/sh\nprintf 'sda\\n'\n"), 0700); err != nil {
		t.Fatal(err)
	}
	w := &WorkloadManager{
		FindmntPath: findmnt,
		LsblkPath:   lsblk,
		Stat: func(path string) (os.FileInfo, error) {
			if path != "/dev/sda" {
				t.Fatalf("stat path = %q", path)
			}
			return blockDeviceInfo{name: "sda"}, nil
		},
	}
	device, err := w.FlashDevice(context.Background())
	if err != nil {
		t.Fatal(err)
	}
	if device != "/dev/sda" {
		t.Fatalf("device = %q", device)
	}
}
