package mysql

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

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

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

func openFacilityTestDB(t *testing.T) *gorm.DB {
	t.Helper()
	dsn := fmt.Sprintf("file:facility_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(&facility.Facility{}); err != nil {
		t.Fatalf("auto migrate: %v", err)
	}
	return db
}

func TestNewFacilityRepository(t *testing.T) {
	db := openFacilityTestDB(t)
	repo := NewFacilityRepository(db)
	if repo == nil || repo.db == nil {
		t.Fatalf("expected repository initialized")
	}
}

func TestFacilityRepositoryCreate(t *testing.T) {
	db := openFacilityTestDB(t)
	repo := NewFacilityRepository(db)
	row := &facility.Facility{Category: "HEMS", Name: "Stretcher", Type: "Cabin", Length: "2m", Weight: "5kg"}

	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 := &facility.Facility{Category: "HEMS", Name: "Inactive", Type: "Cabin", 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 facility persisted as false")
	}

	sqlDB, _ := db.DB()
	_ = sqlDB.Close()
	if err := repo.Create(context.Background(), &facility.Facility{Category: "HEMS", Name: "AfterClose", Type: "X"}); err == nil {
		t.Fatalf("expected error on closed DB")
	}
}

func TestFacilityRepositoryUpdate(t *testing.T) {
	db := openFacilityTestDB(t)
	repo := NewFacilityRepository(db)
	row := &facility.Facility{Category: "HEMS", Name: "Old", Type: "Cabin"}
	if err := repo.Create(context.Background(), row); err != nil {
		t.Fatalf("seed create: %v", err)
	}

	row.Name = "New"
	row.Type = "External"
	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" || loaded.Type != "External" {
		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 TestFacilityRepositoryDelete(t *testing.T) {
	db := openFacilityTestDB(t)
	repo := NewFacilityRepository(db)
	row := &facility.Facility{Category: "HEMS", Name: "DeleteMe", Type: "Cabin"}
	if err := repo.Create(context.Background(), row); err != nil {
		t.Fatalf("seed create: %v", err)
	}

	if err := repo.Delete(context.Background(), row.ID, nil); 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 row deleted")
	}
}

func TestFacilityRepositoryGetByID(t *testing.T) {
	t.Run("found", func(t *testing.T) {
		db := openFacilityTestDB(t)
		repo := NewFacilityRepository(db)
		row := &facility.Facility{Category: "HEMS", Name: "Found", Type: "Cabin"}
		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 := openFacilityTestDB(t)
		repo := NewFacilityRepository(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 := openFacilityTestDB(t)
		repo := NewFacilityRepository(db)
		sqlDB, _ := db.DB()
		_ = sqlDB.Close()

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

func TestFacilityRepositoryList(t *testing.T) {
	t.Run("success without limit", func(t *testing.T) {
		db := openFacilityTestDB(t)
		repo := NewFacilityRepository(db)
		_ = repo.Create(context.Background(), &facility.Facility{Category: "HEMS", Name: "A", Type: "Cabin", Length: "1m", Weight: "1kg"})
		_ = repo.Create(context.Background(), &facility.Facility{Category: "Dry", Name: "B", Type: "External", Length: "2m", Weight: "2kg"})

		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 category sort and limit", func(t *testing.T) {
		db := openFacilityTestDB(t)
		repo := NewFacilityRepository(db)
		_ = repo.Create(context.Background(), &facility.Facility{Category: "HEMS", Name: "Main Basket", Type: "Basket", Length: "12", Weight: "30"})
		_ = repo.Create(context.Background(), &facility.Facility{Category: "Dry", Name: "Dry Basket", Type: "Basket", Length: "10", Weight: "20"})

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

	t.Run("count error", func(t *testing.T) {
		db := openFacilityTestDB(t)
		repo := NewFacilityRepository(db)
		if err := db.Migrator().DropTable(&facility.Facility{}); 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 := openFacilityTestDB(t)
		repo := NewFacilityRepository(db)
		_ = repo.Create(context.Background(), &facility.Facility{Category: "HEMS", Name: "Main", Type: "Basket"})

		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 := openFacilityTestDB(t)
		repo := NewFacilityRepository(db)
		_ = repo.Create(context.Background(), &facility.Facility{Category: "HEMS", Name: "Gamma", Type: "A", IsActive: true})
		_ = repo.Create(context.Background(), &facility.Facility{Category: "HEMS", Name: "Beta", Type: "A", SortKey: intPtrFacility(0), IsActive: true})
		_ = repo.Create(context.Background(), &facility.Facility{Category: "HEMS", Name: "Charlie", Type: "A", SortKey: intPtrFacility(2), IsActive: true})
		_ = repo.Create(context.Background(), &facility.Facility{Category: "HEMS", Name: "Alpha", Type: "A", SortKey: intPtrFacility(1), IsActive: true})
		_ = repo.Create(context.Background(), &facility.Facility{Category: "HEMS", Name: "Zulu", Type: "A", IsActive: false})
		_ = repo.Create(context.Background(), &facility.Facility{Category: "HEMS", Name: "Bravo", Type: "A", SortKey: intPtrFacility(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 intPtrFacility(v int) *int { return &v }
