package fs_test

import (
	"os"
	"path/filepath"
	"slices"
	"testing"

	"galaxy/game/internal/repo/fs"
	"galaxy/util"

	"github.com/stretchr/testify/assert"
)

const (
	lockFile = ".lock"
)

type sampleData struct {
	data []byte
}

func (sd *sampleData) UnmarshalBinary(data []byte) error {
	sd.data = slices.Clone(data)
	return nil
}

func (sd sampleData) MarshalBinary() (data []byte, err error) {
	return sd.data, nil
}

func TestNewFileStorageSuccess(t *testing.T) {
	root, cleanup := util.CreateWorkDir(t)
	defer cleanup()
	_, err := fs.NewFileStorage(root)
	assert.NoError(t, err)
}

func TestLock(t *testing.T) {
	root, cleanup := util.CreateWorkDir(t)
	defer cleanup()
	fs, err := fs.NewFileStorage(root)
	assert.NoError(t, err, "create file storage")
	unlock, err := fs.Lock()
	assert.NoError(t, err, "acquire lock")
	lockPath := filepath.Join(root, lockFile)
	assert.FileExists(t, lockPath, "lock file should be created")
	err = unlock()
	assert.NoError(t, err, "unlocking existing lock")
	assert.NoFileExists(t, lockPath, "lock file must be removed")
}

func TestExist(t *testing.T) {
	root, cleanup := util.CreateWorkDir(t)
	defer cleanup()

	fileName := "some-file.ext"
	if err := os.WriteFile(filepath.Join(root, fileName), []byte{1, 2, 3, 4}, os.ModePerm); err != nil {
		t.Fatal(err)
	}

	fs, err := fs.NewFileStorage(root)
	assert.NoError(t, err, "create file storage")

	exist, err := fs.Exists(fileName)
	assert.NoError(t, err)
	assert.True(t, exist)

	exist, err = fs.Exists("random/path")
	assert.NoError(t, err)
	assert.False(t, exist)
}

func TestWrite(t *testing.T) {
	root, cleanup := util.CreateWorkDir(t)
	defer cleanup()

	fs, err := fs.NewFileStorage(root)
	assert.NoError(t, err, "create file storage: %s", err)

	unlock, err := fs.Lock()
	assert.NoError(t, err, "acquire lock: %s", err)

	dirName := "some-dir"
	if err := os.Mkdir(filepath.Join(root, dirName), os.ModePerm); err != nil {
		t.Fatal(err)
	}

	for _, tc := range []struct {
		path string
		err  string
	}{
		{path: "file-1.ext"},
		{path: "/dir/file-2.ext"},
		{path: "dir/subdir/file-3.ext"},
		{path: lockFile, err: "write to the lock file"},
		{path: dirName, err: "wrong type"},
		{path: "/" + dirName, err: "wrong type"},
	} {
		t.Run(tc.path, func(t *testing.T) {
			sd := &sampleData{[]byte{0, 1, 2, 3}}
			err = fs.Write(tc.path, sd)
			if tc.err == "" {
				assert.NoError(t, err)
				assert.FileExists(t, filepath.Join(root, tc.path), "the written file should exist")
			} else if tc.err != "" {
				assert.ErrorContains(t, err, tc.err)
			}
		})
	}

	assert.NoError(t, unlock(), "unlocking existing lock")
}

func TestRead(t *testing.T) {
	root, cleanup := util.CreateWorkDir(t)
	defer cleanup()

	sd := new(sampleData)

	fs, err := fs.NewFileStorage(root)
	assert.NoError(t, err, "create file storage: %s", err)

	assert.EqualError(t, fs.Read("some.file", sd), "lock must be acquired before read")

	unlock, err := fs.Lock()
	assert.NoError(t, err, "acquire lock: %s", err)

	dirName := "some-dir"
	if err := os.Mkdir(filepath.Join(root, dirName), os.ModePerm); err != nil {
		t.Fatal(err)
	}

	fileName := "some-file.ext"
	if err := os.WriteFile(filepath.Join(root, fileName), []byte{1, 2, 3, 4}, os.ModePerm); err != nil {
		t.Fatal(err)
	}

	for _, tc := range []struct {
		path string
		err  string
	}{
		{path: fileName},
		{path: "/" + fileName},
		{path: lockFile, err: "read from the lock file"},
		{path: "dir/subdir/file-3.ext", err: "no such file"},
		{path: lockFile, err: "read from the lock file"},
		{path: dirName, err: "is a directory"},
	} {
		t.Run(tc.path, func(t *testing.T) {
			err = fs.Read(tc.path, sd)
			if tc.err == "" {
				assert.NoError(t, err)
				assert.FileExists(t, filepath.Join(root, tc.path), "the written file should exist")
			} else if tc.err != "" {
				assert.ErrorContains(t, err, tc.err)
			}
		})
	}
	assert.NoError(t, unlock(), "unlocking existing lock")
}

func TestWriteErrorWithoutLock(t *testing.T) {
	root, cleanup := util.CreateWorkDir(t)
	defer cleanup()
	fs, err := fs.NewFileStorage(root)
	assert.NoError(t, err, "create file storage")
	sd := &sampleData{[]byte{0, 1, 2, 3}}
	err = fs.Write("some/path", sd)
	assert.Error(t, err, "should return error when no lock acquired")
	assert.EqualError(t, err, "lock must be acquired before write")
}

func TestNewFileStorageErrorNotExists(t *testing.T) {
	_, err := fs.NewFileStorage(filepath.Join(os.TempDir(), "non-existent-dir"))
	assert.Error(t, err)
}

func TestNewFileStorageErrorNotADirectory(t *testing.T) {
	f, err := os.CreateTemp("", "fs-test-file")
	if err != nil {
		t.Fatal(err)
	}
	if err := f.Close(); err != nil {
		t.Fatal(err)
	}
	_, err = fs.NewFileStorage(f.Name())
	assert.Error(t, err)
	if err := os.Remove(f.Name()); err != nil {
		t.Fatal(err)
	}
}

func TestNewFileStorageErrorNoAccess(t *testing.T) {
	_, err := fs.NewFileStorage("/some/random/dir")
	assert.Error(t, err)
}
