package mysql

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

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

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

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

func TestNewHealthInsuranceCompaniesRepository(t *testing.T) {
	db := openHealthInsuranceCompaniesTestDB(t)
	repo := NewHealthInsuranceCompaniesRepository(db)
	if repo == nil || repo.db == nil {
		t.Fatalf("expected repository initialized")
	}
}

func TestHealthInsuranceCompaniesRepositoryCreate(t *testing.T) {
	db := openHealthInsuranceCompaniesTestDB(t)
	repo := NewHealthInsuranceCompaniesRepository(db)
	row := &health_insurance_companies.HealthInsuranceCompany{Name: "Main", State: "Berlin"}

	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 := &health_insurance_companies.HealthInsuranceCompany{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 hic persisted as false")
	}

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

func TestHealthInsuranceCompaniesRepositoryUpdate(t *testing.T) {
	db := openHealthInsuranceCompaniesTestDB(t)
	repo := NewHealthInsuranceCompaniesRepository(db)
	row := &health_insurance_companies.HealthInsuranceCompany{Name: "Old", State: "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 TestHealthInsuranceCompaniesRepositoryDelete(t *testing.T) {
	db := openHealthInsuranceCompaniesTestDB(t)
	repo := NewHealthInsuranceCompaniesRepository(db)
	row := &health_insurance_companies.HealthInsuranceCompany{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 TestHealthInsuranceCompaniesRepositoryGetByID(t *testing.T) {
	t.Run("found", func(t *testing.T) {
		db := openHealthInsuranceCompaniesTestDB(t)
		repo := NewHealthInsuranceCompaniesRepository(db)
		row := &health_insurance_companies.HealthInsuranceCompany{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 := openHealthInsuranceCompaniesTestDB(t)
		repo := NewHealthInsuranceCompaniesRepository(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 := openHealthInsuranceCompaniesTestDB(t)
		repo := NewHealthInsuranceCompaniesRepository(db)
		sqlDB, _ := db.DB()
		_ = sqlDB.Close()

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

func TestHealthInsuranceCompaniesRepositoryList(t *testing.T) {
	t.Run("success without limit", func(t *testing.T) {
		db := openHealthInsuranceCompaniesTestDB(t)
		repo := NewHealthInsuranceCompaniesRepository(db)
		_ = repo.Create(context.Background(), &health_insurance_companies.HealthInsuranceCompany{Name: "C", State: "Gamma"})
		_ = repo.Create(context.Background(), &health_insurance_companies.HealthInsuranceCompany{Name: "A", State: "Alpha"})

		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 := openHealthInsuranceCompaniesTestDB(t)
		repo := NewHealthInsuranceCompaniesRepository(db)
		_ = repo.Create(context.Background(), &health_insurance_companies.HealthInsuranceCompany{Name: "Main Base", State: "Center"})
		_ = repo.Create(context.Background(), &health_insurance_companies.HealthInsuranceCompany{Name: "Backup", State: "Secondary"})

		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 := openHealthInsuranceCompaniesTestDB(t)
		repo := NewHealthInsuranceCompaniesRepository(db)
		if err := db.Migrator().DropTable(&health_insurance_companies.HealthInsuranceCompany{}); 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 := openHealthInsuranceCompaniesTestDB(t)
		repo := NewHealthInsuranceCompaniesRepository(db)
		_ = repo.Create(context.Background(), &health_insurance_companies.HealthInsuranceCompany{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 := openHealthInsuranceCompaniesTestDB(t)
		repo := NewHealthInsuranceCompaniesRepository(db)
		_ = repo.Create(context.Background(), &health_insurance_companies.HealthInsuranceCompany{Name: "Gamma", IsActive: true})
		_ = repo.Create(context.Background(), &health_insurance_companies.HealthInsuranceCompany{Name: "Beta", SortKey: intPtrHICRepo(0), IsActive: true})
		_ = repo.Create(context.Background(), &health_insurance_companies.HealthInsuranceCompany{Name: "Charlie", SortKey: intPtrHICRepo(2), IsActive: true})
		_ = repo.Create(context.Background(), &health_insurance_companies.HealthInsuranceCompany{Name: "Alpha", SortKey: intPtrHICRepo(1), IsActive: true})
		_ = repo.Create(context.Background(), &health_insurance_companies.HealthInsuranceCompany{Name: "Zulu", IsActive: false})
		_ = repo.Create(context.Background(), &health_insurance_companies.HealthInsuranceCompany{Name: "Bravo", SortKey: intPtrHICRepo(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 intPtrHICRepo(v int) *int { return &v }
