package mysql

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

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

	"wucher/internal/domain/federal_state"
	"wucher/internal/domain/land"
	"wucher/internal/shared/pkg/uuidv7"
)

func openFederalStateTestDB(t *testing.T) *gorm.DB {
	t.Helper()
	dsn := fmt.Sprintf("file:federal_state_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(&land.Land{}); err != nil {
		t.Fatalf("auto migrate land: %v", err)
	}
	if err := db.AutoMigrate(&federal_state.FederalState{}); err != nil {
		t.Fatalf("auto migrate: %v", err)
	}
	return db
}

func TestNewFederalStateRepository(t *testing.T) {
	db := openFederalStateTestDB(t)
	repo := NewFederalStateRepository(db)
	if repo == nil || repo.db == nil {
		t.Fatalf("expected repository initialized")
	}
}

func TestFederalStateRepositoryCreate(t *testing.T) {
	db := openFederalStateTestDB(t)
	repo := NewFederalStateRepository(db)
	row := &federal_state.FederalState{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 := &federal_state.FederalState{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 federal state persisted as false")
	}

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

func TestFederalStateRepositoryUpdate(t *testing.T) {
	db := openFederalStateTestDB(t)
	repo := NewFederalStateRepository(db)
	row := &federal_state.FederalState{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 TestFederalStateRepositoryDelete(t *testing.T) {
	db := openFederalStateTestDB(t)
	repo := NewFederalStateRepository(db)
	row := &federal_state.FederalState{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 TestFederalStateRepositoryDelete_BlockedWhenUsedByInsurancePatientData(t *testing.T) {
	db := openFederalStateTestDB(t)

	if err := db.Exec(`CREATE TABLE IF NOT EXISTS insurance_patient_data (
		id BLOB PRIMARY KEY,
		federal_state_id BLOB NULL,
		deleted_at DATETIME NULL
	)`).Error; err != nil {
		t.Fatalf("create insurance_patient_data table: %v", err)
	}
	repo := NewFederalStateRepository(db)

	row := &federal_state.FederalState{Name: "InUse"}
	if err := repo.Create(context.Background(), row); err != nil {
		t.Fatalf("seed create: %v", err)
	}
	if err := db.Table("insurance_patient_data").Create(map[string]any{
		"id":               uuidv7.MustBytes(),
		"federal_state_id": row.ID,
		"deleted_at":       nil,
	}).Error; err != nil {
		t.Fatalf("seed insurance_patient_data: %v", err)
	}

	err := repo.Delete(context.Background(), row.ID, uuidv7.MustBytes())
	if err == nil {
		t.Fatalf("expected delete to be blocked")
	}
	if !strings.Contains(strings.ToLower(err.Error()), "insurance patient data") {
		t.Fatalf("expected dependency detail in error, got: %v", err)
	}
}

func TestFederalStateRepositoryDelete_BlockedWhenUsedByICAO(t *testing.T) {
	db := openFederalStateTestDB(t)

	if err := db.Exec(`CREATE TABLE IF NOT EXISTS icaos (
		id BLOB PRIMARY KEY,
		federal_state_id BLOB NULL,
		deleted_at DATETIME NULL
	)`).Error; err != nil {
		t.Fatalf("create icaos table: %v", err)
	}
	repo := NewFederalStateRepository(db)

	row := &federal_state.FederalState{Name: "InUseByICAO"}
	if err := repo.Create(context.Background(), row); err != nil {
		t.Fatalf("seed create: %v", err)
	}
	if err := db.Table("icaos").Create(map[string]any{
		"id":               uuidv7.MustBytes(),
		"federal_state_id": row.ID,
		"deleted_at":       nil,
	}).Error; err != nil {
		t.Fatalf("seed icaos: %v", err)
	}

	err := repo.Delete(context.Background(), row.ID, uuidv7.MustBytes())
	if err == nil {
		t.Fatalf("expected delete to be blocked")
	}
	if !strings.Contains(strings.ToLower(err.Error()), "icaos") {
		t.Fatalf("expected dependency detail in error, got: %v", err)
	}
}

func TestFederalStateRepositoryDelete_BlockedWhenUsedByLegacyStateColumn(t *testing.T) {
	db := openFederalStateTestDB(t)

	if err := db.Exec(`CREATE TABLE IF NOT EXISTS health_insurance_companies (
		id BLOB PRIMARY KEY,
		state TEXT NULL,
		deleted_at DATETIME NULL
	)`).Error; err != nil {
		t.Fatalf("create health_insurance_companies table: %v", err)
	}
	repo := NewFederalStateRepository(db)

	row := &federal_state.FederalState{Name: "Bayern"}
	if err := repo.Create(context.Background(), row); err != nil {
		t.Fatalf("seed create: %v", err)
	}
	if err := db.Table("health_insurance_companies").Create(map[string]any{
		"id":         uuidv7.MustBytes(),
		"state":      "Bayern",
		"deleted_at": nil,
	}).Error; err != nil {
		t.Fatalf("seed health_insurance_companies: %v", err)
	}

	err := repo.Delete(context.Background(), row.ID, uuidv7.MustBytes())
	if err == nil {
		t.Fatalf("expected delete to be blocked")
	}
	if !strings.Contains(strings.ToLower(err.Error()), "health insurance companies") {
		t.Fatalf("expected dependency detail in error, got: %v", err)
	}
}

func TestFederalStateRepositoryGetByID(t *testing.T) {
	t.Run("found", func(t *testing.T) {
		db := openFederalStateTestDB(t)
		repo := NewFederalStateRepository(db)
		row := &federal_state.FederalState{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 := openFederalStateTestDB(t)
		repo := NewFederalStateRepository(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 := openFederalStateTestDB(t)
		repo := NewFederalStateRepository(db)
		sqlDB, _ := db.DB()
		_ = sqlDB.Close()

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

func TestFederalStateRepositoryList(t *testing.T) {
	t.Run("success without limit", func(t *testing.T) {
		db := openFederalStateTestDB(t)
		repo := NewFederalStateRepository(db)
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "C"})
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "A"})

		rows, total, err := repo.List(context.Background(), "", "", 0, 0, nil, "")
		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 := openFederalStateTestDB(t)
		repo := NewFederalStateRepository(db)
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Main Base"})
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Backup"})

		rows, total, err := repo.List(context.Background(), "Main", "name DESC", 1, 0, nil, "")
		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 := openFederalStateTestDB(t)
		repo := NewFederalStateRepository(db)
		if err := db.Migrator().DropTable(&federal_state.FederalState{}); err != nil {
			t.Fatalf("drop table: %v", err)
		}

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

	t.Run("find error", func(t *testing.T) {
		db := openFederalStateTestDB(t)
		repo := NewFederalStateRepository(db)
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Main"})

		if _, _, err := repo.List(context.Background(), "", "name ASC, )", 10, 0, nil, ""); 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 := openFederalStateTestDB(t)
		repo := NewFederalStateRepository(db)
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Gamma", IsActive: true})
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Beta", SortKey: intPtrFederalStateRepo(0), IsActive: true})
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Charlie", SortKey: intPtrFederalStateRepo(2), IsActive: true})
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Alpha", SortKey: intPtrFederalStateRepo(1), IsActive: true})
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Zulu", IsActive: false})
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Bravo", SortKey: intPtrFederalStateRepo(9), IsActive: false})

		rows, total, err := repo.List(context.Background(), "", "", 0, 0, nil, "")
		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)
			}
		}
	})

	t.Run("success with land_id and land_name filter", func(t *testing.T) {
		db := openFederalStateTestDB(t)
		repo := NewFederalStateRepository(db)
		deLand := &land.Land{Name: "Germany", LandISOCode: "DE"}
		frLand := &land.Land{Name: "France", LandISOCode: "FR"}
		if err := db.Create(deLand).Error; err != nil {
			t.Fatalf("create de land: %v", err)
		}
		if err := db.Create(frLand).Error; err != nil {
			t.Fatalf("create fr land: %v", err)
		}

		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Bayern", LandID: deLand.ID})
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Berlin", LandID: deLand.ID})
		_ = repo.Create(context.Background(), &federal_state.FederalState{Name: "Paris", LandID: frLand.ID})

		rows, total, err := repo.List(context.Background(), "", "federal_states.name ASC", 10, 0, deLand.ID, "Ger")
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if total != 2 || len(rows) != 2 {
			t.Fatalf("unexpected filtered result total=%d len=%d", total, len(rows))
		}
		for _, row := range rows {
			if row.Name == "Paris" {
				t.Fatalf("expected france row excluded")
			}
		}
	})
}

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