package mysql

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

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

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

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

func TestNewHospitalRepository(t *testing.T) {
	db := openHospitalTestDB(t)
	repo := NewHospitalRepository(db)
	if repo == nil || repo.db == nil {
		t.Fatalf("expected repository initialized")
	}
}

func TestHospitalRepositoryCreate(t *testing.T) {
	db := openHospitalTestDB(t)
	repo := NewHospitalRepository(db)
	row := &hospital.Hospital{Name: "RSUD Kota", Address: "Jl. Merdeka", LandlineNumber: "021123", MobileNumber: "08123", Email: "a@b.c"}

	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 := &hospital.Hospital{Name: "RS Inactive", IsActive: false}
	if err := repo.Create(context.Background(), inactive); err != nil {
		t.Fatalf("create inactive: %v", err)
	}
	loadedInactive, err := repo.GetByID(context.Background(), inactive.ID)
	if err != nil || loadedInactive == nil {
		t.Fatalf("expected inactive row loadable")
	}
	if loadedInactive.IsActive {
		t.Fatalf("expected inactive row persisted with is_active=false")
	}

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

func TestHospitalRepositoryUpdate(t *testing.T) {
	db := openHospitalTestDB(t)
	repo := NewHospitalRepository(db)
	row := &hospital.Hospital{Name: "Old", Address: "Old Addr"}
	if err := repo.Create(context.Background(), row); err != nil {
		t.Fatalf("seed create: %v", err)
	}

	row.Name = "New"
	row.Address = "New Addr"
	row.LandlineNumber = "021999"
	row.MobileNumber = "08999"
	row.Email = "new@hospital.local"
	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.Address != "New Addr" || loaded.LandlineNumber != "021999" || loaded.MobileNumber != "08999" || loaded.Email != "new@hospital.local" {
		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 TestHospitalRepositoryDelete(t *testing.T) {
	db := openHospitalTestDB(t)
	repo := NewHospitalRepository(db)
	row := &hospital.Hospital{Name: "DeleteMe", Address: "A"}
	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 TestHospitalRepositoryGetByID(t *testing.T) {
	t.Run("found", func(t *testing.T) {
		db := openHospitalTestDB(t)
		repo := NewHospitalRepository(db)
		row := &hospital.Hospital{Name: "Found", Address: "Address", Email: "found@hospital.local"}
		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" || got.Address != "Address" || got.Email != "found@hospital.local" {
			t.Fatalf("expected row found")
		}
	})

	t.Run("not found", func(t *testing.T) {
		db := openHospitalTestDB(t)
		repo := NewHospitalRepository(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 := openHospitalTestDB(t)
		repo := NewHospitalRepository(db)
		sqlDB, _ := db.DB()
		_ = sqlDB.Close()

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

func TestHospitalRepositoryList(t *testing.T) {
	t.Run("success without limit", func(t *testing.T) {
		db := openHospitalTestDB(t)
		repo := NewHospitalRepository(db)
		_ = repo.Create(context.Background(), &hospital.Hospital{Name: "Charlie Hospital", Address: "Gamma"})
		_ = repo.Create(context.Background(), &hospital.Hospital{Name: "Alpha Hospital", Address: "Beta"})

		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 := openHospitalTestDB(t)
		repo := NewHospitalRepository(db)
		_ = repo.Create(context.Background(), &hospital.Hospital{Name: "Main Hospital", Address: "Center"})
		_ = repo.Create(context.Background(), &hospital.Hospital{Name: "Backup", Address: "Secondary"})

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

	t.Run("count error", func(t *testing.T) {
		db := openHospitalTestDB(t)
		repo := NewHospitalRepository(db)
		if err := db.Migrator().DropTable(&hospital.Hospital{}); 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 := openHospitalTestDB(t)
		repo := NewHospitalRepository(db)
		_ = repo.Create(context.Background(), &hospital.Hospital{Name: "Main"})

		if _, _, err := repo.List(context.Background(), "", "hospital_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 := openHospitalTestDB(t)
		repo := NewHospitalRepository(db)
		_ = repo.Create(context.Background(), &hospital.Hospital{Name: "Gamma", IsActive: true})
		_ = repo.Create(context.Background(), &hospital.Hospital{Name: "Beta", SortKey: intPtrHospitalRepo(0), IsActive: true})
		_ = repo.Create(context.Background(), &hospital.Hospital{Name: "Charlie", SortKey: intPtrHospitalRepo(2), IsActive: true})
		_ = repo.Create(context.Background(), &hospital.Hospital{Name: "Alpha", SortKey: intPtrHospitalRepo(1), IsActive: true})
		_ = repo.Create(context.Background(), &hospital.Hospital{Name: "Zulu", IsActive: false})
		_ = repo.Create(context.Background(), &hospital.Hospital{Name: "Bravo", SortKey: intPtrHospitalRepo(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 intPtrHospitalRepo(v int) *int { return &v }
