package mysql

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

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

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

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

func TestNewMedicineRepository(t *testing.T) {
	db := openMedicineTestDB(t)
	repo := NewMedicineRepository(db)
	if repo == nil || repo.db == nil {
		t.Fatalf("expected repository initialized")
	}
}

func TestMedicineRepositoryCreate(t *testing.T) {
	db := openMedicineTestDB(t)
	repo := NewMedicineRepository(db)
	row := &medicine.Medicine{Name: "Paracetamol", Pack:"500mg", Unit: "tablet", Column: 1}

	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 := &medicine.Medicine{Name: "Ibuprofen", Pack: "200mg", Unit: "capsule", 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 || gotInactive.Unit != "capsule" {
		t.Fatalf("expected inactive medicine persisted as false")
	}

	sqlDB, _ := db.DB()
	_ = sqlDB.Close()
	if err := repo.Create(context.Background(), &medicine.Medicine{Name: "AfterClose", Pack: "10mg", Column: 2}); err == nil {
		t.Fatalf("expected error on closed DB")
	}
}

func TestMedicineRepositoryUpdate(t *testing.T) {
	db := openMedicineTestDB(t)
	repo := NewMedicineRepository(db)
	row := &medicine.Medicine{Name: "Old", Pack: "100mg", Column: 1}
	if err := repo.Create(context.Background(), row); err != nil {
		t.Fatalf("seed create: %v", err)
	}

	row.Name = "New"
	row.Pack = "250mg"
	row.Unit = "solution"
	row.Column = 3
	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.Pack != "250mg" || loaded.Column != 3 {
		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 TestMedicineRepositoryDelete(t *testing.T) {
	db := openMedicineTestDB(t)
	repo := NewMedicineRepository(db)
	row := &medicine.Medicine{Name: "DeleteMe", Pack: "500mg", Unit: "tablet", Column: 2}
	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 TestMedicineRepositoryGetByID(t *testing.T) {
	t.Run("found", func(t *testing.T) {
		db := openMedicineTestDB(t)
		repo := NewMedicineRepository(db)
		row := &medicine.Medicine{Name: "Found", Pack: "10mg", Unit: "tablet", Column: 8}
		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.Pack != "10mg" || got.Unit != "tablet" || got.Column != 8 {
			t.Fatalf("expected row found")
		}
	})

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

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

func TestMedicineRepositoryList(t *testing.T) {
	t.Run("success without limit", func(t *testing.T) {
		db := openMedicineTestDB(t)
		repo := NewMedicineRepository(db)
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "C", Pack:"1mg", Unit: "tablet", Column: 11})
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "A", Pack:"2mg", Unit: "capsule", Column: 12})

		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 := openMedicineTestDB(t)
		repo := NewMedicineRepository(db)
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Main", Pack:"500mg", Unit: "tablet", Column: 77})
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Backup", Pack:"200mg", Unit: "capsule", Column: 10})

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

	t.Run("success filtering by unit field", func(t *testing.T) {
		db := openMedicineTestDB(t)
		repo := NewMedicineRepository(db)
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Tablet A", Pack: "100mg", Unit: "tablet", Column: 1})
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Capsule B", Pack: "200mg", Unit: "capsule", Column: 2})
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Spray C", Pack: "50mg", Unit: "spray", Column: 3})

		rows, total, err := repo.List(context.Background(), "spray", "", 10, 0)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if total != 1 || len(rows) != 1 || rows[0].Unit != "spray" {
			t.Fatalf("unexpected filtered result by unit")
		}

		rows, total, err = repo.List(context.Background(), "capsule", "", 10, 0)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if total != 1 || len(rows) != 1 || rows[0].Unit != "capsule" {
			t.Fatalf("unexpected filtered result by unit")
		}
	})

	t.Run("count error", func(t *testing.T) {
		db := openMedicineTestDB(t)
		repo := NewMedicineRepository(db)
		if err := db.Migrator().DropTable(&medicine.Medicine{}); 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 := openMedicineTestDB(t)
		repo := NewMedicineRepository(db)
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Main", Pack:"100mg", Unit: "tablet", Column: 2})

		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 then name ascending", func(t *testing.T) {
		db := openMedicineTestDB(t)
		repo := NewMedicineRepository(db)
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Gamma", Unit: "tablet", IsActive: true})
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Beta", Unit: "tablet", IsActive: true})
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Charlie", Unit: "tablet", IsActive: true})
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Alpha", Unit: "tablet", IsActive: true})
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Zulu", Unit: "tablet", IsActive: false})
		_ = repo.Create(context.Background(), &medicine.Medicine{Name: "Bravo", Unit: "tablet", 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{"Alpha", "Beta", "Charlie", "Gamma", "Bravo", "Zulu"}
		for i := range wantOrder {
			if gotOrder[i] != wantOrder[i] {
				t.Fatalf("unexpected default order: got=%v want=%v", gotOrder, wantOrder)
			}
		}
	})
}
