package local

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

	"git.tswf.io/infra/go-synapse-backupper/pkg/domain"
)

func TestLocalSink_BeginOpensTmpInSameDirectory(t *testing.T) {
	dir := t.TempDir()
	sink := NewLocalSink(dir)

	transaction, err := sink.Begin("backup.sql")
	if err != nil {
		t.Fatalf("Begin failed: %v", err)
	}
	defer func() { _ = transaction.Abort() }()

	tmpPath := filepath.Join(dir, "backup.sql.tmp")
	if _, err := os.Stat(tmpPath); os.IsNotExist(err) {
		t.Fatalf("expected tmp file to exist at %s", tmpPath)
	}
}

func TestLocalSink_WriteStreamsBytes(t *testing.T) {
	dir := t.TempDir()
	sink := NewLocalSink(dir)

	transaction, err := sink.Begin("backup.sql")
	if err != nil {
		t.Fatalf("Begin failed: %v", err)
	}
	defer func() { _ = transaction.Abort() }()

	data := []byte("hello world")
	written, err := transaction.Write(data)
	if err != nil {
		t.Fatalf("Write failed: %v", err)
	}
	if written != len(data) {
		t.Fatalf("expected %d bytes written, got %d", len(data), written)
	}
}

func TestLocalSink_CommitSequence(t *testing.T) {
	dir := t.TempDir()
	sink := NewLocalSink(dir)

	transaction, err := sink.Begin("backup.sql")
	if err != nil {
		t.Fatalf("Begin failed: %v", err)
	}

	data := []byte("persistent data")
	if _, err := transaction.Write(data); err != nil {
		t.Fatalf("Write failed: %v", err)
	}

	tmpPath := filepath.Join(dir, "backup.sql.tmp")
	tmpInfo, err := os.Stat(tmpPath)
	if err != nil {
		t.Fatalf("stat tmp file failed: %v", err)
	}

	if err := transaction.Commit(); err != nil {
		t.Fatalf("Commit failed: %v", err)
	}

	finalPath := filepath.Join(dir, "backup.sql")
	if _, err := os.Stat(tmpPath); !os.IsNotExist(err) {
		t.Fatalf("expected tmp file to be absent after commit")
	}

	finalInfo, err := os.Stat(finalPath)
	if err != nil {
		t.Fatalf("expected final file to exist after commit: %v", err)
	}

	if !os.SameFile(tmpInfo, finalInfo) {
		t.Fatalf("expected final file to be the same inode as tmp file before rename")
	}
}

func TestLocalSink_AbortIsIdempotent(t *testing.T) {
	dir := t.TempDir()
	sink := NewLocalSink(dir)

	transaction, err := sink.Begin("backup.sql")
	if err != nil {
		t.Fatalf("Begin failed: %v", err)
	}

	if _, err := transaction.Write([]byte("discard me")); err != nil {
		t.Fatalf("Write failed: %v", err)
	}

	if err := transaction.Abort(); err != nil {
		t.Fatalf("first Abort failed: %v", err)
	}
	if err := transaction.Abort(); err != nil {
		t.Fatalf("second Abort should be idempotent: %v", err)
	}

	tmpPath := filepath.Join(dir, "backup.sql.tmp")
	finalPath := filepath.Join(dir, "backup.sql")
	if _, err := os.Stat(tmpPath); !os.IsNotExist(err) {
		t.Fatalf("expected tmp file to be absent after abort")
	}
	if _, err := os.Stat(finalPath); !os.IsNotExist(err) {
		t.Fatalf("expected final file to be absent after abort")
	}
}

func TestLocalSink_AbortAfterCommitIsSafe(t *testing.T) {
	dir := t.TempDir()
	sink := NewLocalSink(dir)

	transaction, err := sink.Begin("backup.sql")
	if err != nil {
		t.Fatalf("Begin failed: %v", err)
	}

	if _, err := transaction.Write([]byte("data")); err != nil {
		t.Fatalf("Write failed: %v", err)
	}

	if err := transaction.Commit(); err != nil {
		t.Fatalf("Commit failed: %v", err)
	}

	if err := transaction.Abort(); err != nil {
		t.Fatalf("Abort after commit should be safe: %v", err)
	}

	finalPath := filepath.Join(dir, "backup.sql")
	if _, err := os.Stat(finalPath); err != nil {
		t.Fatalf("expected final file to still exist after abort-after-commit: %v", err)
	}
}

func TestLocalSink_KillWriterMidStreamThenAbortLeavesNoFinal(t *testing.T) {
	dir := t.TempDir()
	sink := NewLocalSink(dir)

	transaction, err := sink.Begin("backup.sql")
	if err != nil {
		t.Fatalf("Begin failed: %v", err)
	}

	if _, err := transaction.Write([]byte("partial")); err != nil {
		t.Fatalf("Write failed: %v", err)
	}

	if err := transaction.Abort(); err != nil {
		t.Fatalf("Abort failed: %v", err)
	}

	tmpPath := filepath.Join(dir, "backup.sql.tmp")
	finalPath := filepath.Join(dir, "backup.sql")
	if _, err := os.Stat(tmpPath); !os.IsNotExist(err) {
		t.Fatalf("expected tmp file to be absent after abort")
	}
	if _, err := os.Stat(finalPath); !os.IsNotExist(err) {
		t.Fatalf("expected final file to be absent after abort")
	}
}

func TestLocalSink_ListAndRemove(t *testing.T) {
	dir := t.TempDir()
	sink := NewLocalSink(dir)

	if err := os.WriteFile(filepath.Join(dir, "a.sql"), []byte("a"), 0o644); err != nil {
		t.Fatalf("setup failed: %v", err)
	}
	if err := os.WriteFile(filepath.Join(dir, "b.sql"), []byte("b"), 0o644); err != nil {
		t.Fatalf("setup failed: %v", err)
	}

	keys, err := sink.List("")
	if err != nil {
		t.Fatalf("List failed: %v", err)
	}
	if len(keys) != 2 {
		t.Fatalf("expected 2 keys, got %d", len(keys))
	}

	if err := sink.Remove("a.sql"); err != nil {
		t.Fatalf("Remove failed: %v", err)
	}

	keys, err = sink.List("")
	if err != nil {
		t.Fatalf("List after remove failed: %v", err)
	}
	if len(keys) != 1 {
		t.Fatalf("expected 1 key after remove, got %d", len(keys))
	}
}

func TestLocalSink_RemoveMissingIsError(t *testing.T) {
	dir := t.TempDir()
	sink := NewLocalSink(dir)

	err := sink.Remove("nonexistent.sql")
	if err == nil {
		t.Fatalf("expected error removing missing file")
	}
}

func TestLocalSink_WriteAfterCommitIsError(t *testing.T) {
	dir := t.TempDir()
	sink := NewLocalSink(dir)

	transaction, err := sink.Begin("backup.sql")
	if err != nil {
		t.Fatalf("Begin failed: %v", err)
	}

	if _, err := transaction.Write([]byte("data")); err != nil {
		t.Fatalf("Write failed: %v", err)
	}

	if err := transaction.Commit(); err != nil {
		t.Fatalf("Commit failed: %v", err)
	}

	if _, err := transaction.Write([]byte("more")); err == nil {
		t.Fatalf("expected error writing after commit")
	}
}

func TestLocalSink_WriteAfterAbortIsError(t *testing.T) {
	dir := t.TempDir()
	sink := NewLocalSink(dir)

	transaction, err := sink.Begin("backup.sql")
	if err != nil {
		t.Fatalf("Begin failed: %v", err)
	}

	if err := transaction.Abort(); err != nil {
		t.Fatalf("Abort failed: %v", err)
	}

	if _, err := transaction.Write([]byte("more")); err == nil {
		t.Fatalf("expected error writing after abort")
	}
}

var (
	_ domain.Sink   = (*localSink)(nil)
	_ domain.SinkTx = (*localSinkTx)(nil)
)
