package mysql

import (
	"context"
	"fmt"
	"testing"
	"time"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"

	"wucher/internal/domain/vocation"
	"wucher/internal/shared/pkg/uuidv7"
)

func openVocationTestDB(t *testing.T) *gorm.DB {
	t.Helper()
	dsn := fmt.Sprintf("file:vocation_test_%d?mode=memory&cache=shared", time.Now().UnixNano())
	db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{
		NowFunc: func() time.Time { return time.Now().UTC() },
	})
	if err != nil {
		t.Fatalf("open sqlite: %v", err)
	}
	if err := db.AutoMigrate(&vocation.Vocation{}); err != nil {
		t.Fatalf("auto migrate: %v", err)
	}
	return db
}

func TestNewVocationRepository(t *testing.T) {
	db := openVocationTestDB(t)
	repo := NewVocationRepository(db)
	if repo == nil || repo.db == nil {
		t.Fatalf("expected repository initialized")
	}
}

func TestVocationRepositoryCreate(t *testing.T) {
	db := openVocationTestDB(t)
	repo := NewVocationRepository(db)
	row := &vocation.Vocation{Name: "Main"}

	if err := repo.Create(context.Background(), row); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(row.ID) == 0 {
		t.Fatalf("expected id set")
	}
	inactive := &vocation.Vocation{Name: "Inactive", IsActive: false}
	if err := repo.Create(context.Background(), inactive); err != nil {
		t.Fatalf("create inactive: %v", err)
	}
	gotInactive, err := repo.GetByID(context.Background(), inactive.ID)
	if err != nil {
		t.Fatalf("get inactive: %v", err)
	}
	if gotInactive == nil || gotInactive.IsActive {
		t.Fatalf("expected inactive vocation persisted as false")
	}

	sqlDB, _ := db.DB()
	_ = sqlDB.Close()
	if err := repo.Create(context.Background(), &vocation.Vocation{Name: "AfterClose"}); err == nil {
		t.Fatalf("expected error on closed DB")
	}
}

func TestVocationRepositoryUpdate(t *testing.T) {
	db := openVocationTestDB(t)
	repo := NewVocationRepository(db)
	row := &vocation.Vocation{Name: "Old"}
	if err := repo.Create(context.Background(), row); err != nil {
		t.Fatalf("seed create: %v", err)
	}

	row.Name = "New"
	if err := repo.Update(context.Background(), row); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	loaded, err := repo.GetByID(context.Background(), row.ID)
	if err != nil || loaded == nil || loaded.Name != "New" {
		t.Fatalf("expected updated row")
	}

	sqlDB, _ := db.DB()
	_ = sqlDB.Close()
	if err := repo.Update(context.Background(), row); err == nil {
		t.Fatalf("expected error on closed DB")
	}
}

func TestVocationRepositoryDelete(t *testing.T) {
	db := openVocationTestDB(t)
	repo := NewVocationRepository(db)
	row := &vocation.Vocation{Name: "DeleteMe"}
	if err := repo.Create(context.Background(), row); err != nil {
		t.Fatalf("seed create: %v", err)
	}
	deletedBy := uuidv7.MustBytes()

	if err := repo.Delete(context.Background(), row.ID, deletedBy); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	got, err := repo.GetByID(context.Background(), row.ID)
	if err != nil {
		t.Fatalf("get by id after delete: %v", err)
	}
	if got != nil {
		t.Fatalf("expected soft deleted row hidden from GetByID")
	}
}

func TestVocationRepositoryGetByID(t *testing.T) {
	t.Run("found", func(t *testing.T) {
		db := openVocationTestDB(t)
		repo := NewVocationRepository(db)
		row := &vocation.Vocation{Name: "Found"}
		if err := repo.Create(context.Background(), row); err != nil {
			t.Fatalf("seed create: %v", err)
		}

		got, err := repo.GetByID(context.Background(), row.ID)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if got == nil || got.Name != "Found" {
			t.Fatalf("expected row found")
		}
	})

	t.Run("not found", func(t *testing.T) {
		db := openVocationTestDB(t)
		repo := NewVocationRepository(db)
		got, err := repo.GetByID(context.Background(), uuidv7.MustBytes())
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if got != nil {
			t.Fatalf("expected nil for not found")
		}
	})

	t.Run("db error", func(t *testing.T) {
		db := openVocationTestDB(t)
		repo := NewVocationRepository(db)
		sqlDB, _ := db.DB()
		_ = sqlDB.Close()

		if _, err := repo.GetByID(context.Background(), uuidv7.MustBytes()); err == nil {
			t.Fatalf("expected error on closed DB")
		}
	})
}

func TestVocationRepositoryList(t *testing.T) {
	t.Run("success without limit", func(t *testing.T) {
		db := openVocationTestDB(t)
		repo := NewVocationRepository(db)
		_ = repo.Create(context.Background(), &vocation.Vocation{Name: "C"})
		_ = repo.Create(context.Background(), &vocation.Vocation{Name: "A"})

		rows, total, err := repo.List(context.Background(), "", "", 0, 0)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if total != 2 || len(rows) != 2 {
			t.Fatalf("expected 2 rows, total=%d len=%d", total, len(rows))
		}
	})

	t.Run("success with filter sort and limit", func(t *testing.T) {
		db := openVocationTestDB(t)
		repo := NewVocationRepository(db)
		_ = repo.Create(context.Background(), &vocation.Vocation{Name: "Main Base"})
		_ = repo.Create(context.Background(), &vocation.Vocation{Name: "Backup"})

		rows, total, err := repo.List(context.Background(), "Main", "name DESC", 1, 0)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if total != 1 || len(rows) != 1 || rows[0].Name != "Main Base" {
			t.Fatalf("unexpected list result")
		}
	})

	t.Run("count error", func(t *testing.T) {
		db := openVocationTestDB(t)
		repo := NewVocationRepository(db)
		if err := db.Migrator().DropTable(&vocation.Vocation{}); err != nil {
			t.Fatalf("drop table: %v", err)
		}

		if _, _, err := repo.List(context.Background(), "", "", 10, 0); err == nil {
			t.Fatalf("expected count error")
		}
	})

	t.Run("find error", func(t *testing.T) {
		db := openVocationTestDB(t)
		repo := NewVocationRepository(db)
		_ = repo.Create(context.Background(), &vocation.Vocation{Name: "Main"})

		if _, _, err := repo.List(context.Background(), "", "name ASC, )", 10, 0); err == nil {
			t.Fatalf("expected find error from invalid sort")
		}
	})

	t.Run("default order active sortkey first and inactive last", func(t *testing.T) {
		db := openVocationTestDB(t)
		repo := NewVocationRepository(db)
		_ = repo.Create(context.Background(), &vocation.Vocation{Name: "Gamma", IsActive: true})
		_ = repo.Create(context.Background(), &vocation.Vocation{Name: "Beta", SortKey: intPtrVocationRepo(0), IsActive: true})
		_ = repo.Create(context.Background(), &vocation.Vocation{Name: "Charlie", SortKey: intPtrVocationRepo(2), IsActive: true})
		_ = repo.Create(context.Background(), &vocation.Vocation{Name: "Alpha", SortKey: intPtrVocationRepo(1), IsActive: true})
		_ = repo.Create(context.Background(), &vocation.Vocation{Name: "Zulu", IsActive: false})
		_ = repo.Create(context.Background(), &vocation.Vocation{Name: "Bravo", SortKey: intPtrVocationRepo(9), IsActive: false})

		rows, total, err := repo.List(context.Background(), "", "", 0, 0)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if total != 6 || len(rows) != 6 {
			t.Fatalf("unexpected total/len total=%d len=%d", total, len(rows))
		}

		gotOrder := []string{rows[0].Name, rows[1].Name, rows[2].Name, rows[3].Name, rows[4].Name, rows[5].Name}
		wantOrder := []string{"Beta", "Alpha", "Charlie", "Gamma", "Bravo", "Zulu"}
		for i := range wantOrder {
			if gotOrder[i] != wantOrder[i] {
				t.Fatalf("unexpected default order: got=%v want=%v", gotOrder, wantOrder)
			}
		}
	})
}

func intPtrVocationRepo(v int) *int { return &v }
