package mysql

import (
	"context"
	"testing"

	"hyapp/internal/testutil/mysqlschema"
)

func TestMigrateAddsActivityOutboxDeliveryColumnsToLegacyTable(t *testing.T) {
	schema := mysqlschema.New(t, mysqlschema.Config{
		EnvVar:         "ACTIVITY_SERVICE_MYSQL_TEST_DSN",
		InitDBPath:     mysqlschema.InitDBPath(t, mysqlschema.CallerFile(t, 1), "..", "..", "..", "deploy", "mysql", "initdb", "001_activity_service.sql"),
		DatabasePrefix: "hyapp_activity_migrate_test",
	})

	// 旧库可能只保留最早的 activity_outbox 形态；迁移必须补齐锁字段和按 event_type 收敛的索引，
	// 否则不同 activity worker 会在同一张 outbox 上互相扫全表或重复抢任务。
	for _, statement := range []string{
		`ALTER TABLE activity_outbox DROP INDEX idx_activity_outbox_event_retry`,
		`ALTER TABLE activity_outbox DROP INDEX idx_activity_outbox_event_lock`,
		`ALTER TABLE activity_outbox DROP INDEX idx_activity_outbox_retention`,
		`ALTER TABLE activity_outbox DROP COLUMN last_error`,
		`ALTER TABLE activity_outbox DROP COLUMN lock_until_ms`,
		`ALTER TABLE activity_outbox DROP COLUMN locked_by`,
	} {
		if _, err := schema.DB.ExecContext(context.Background(), statement); err != nil {
			t.Fatalf("prepare legacy activity_outbox: %v", err)
		}
	}

	repository, err := Open(context.Background(), schema.DSN)
	if err != nil {
		t.Fatalf("open repository: %v", err)
	}
	t.Cleanup(func() { _ = repository.Close() })
	if err := repository.Migrate(context.Background()); err != nil {
		t.Fatalf("Migrate failed: %v", err)
	}
	for _, column := range []string{"locked_by", "lock_until_ms", "last_error"} {
		if hasColumn, err := repository.columnExists(context.Background(), "activity_outbox", column); err != nil || !hasColumn {
			t.Fatalf("%s column missing after migrate: has=%v err=%v", column, hasColumn, err)
		}
	}
	for _, index := range []string{"idx_activity_outbox_event_retry", "idx_activity_outbox_event_lock", "idx_activity_outbox_retention"} {
		if hasIndex, err := repository.indexExists(context.Background(), "activity_outbox", index); err != nil || !hasIndex {
			t.Fatalf("%s missing after migrate: has=%v err=%v", index, hasIndex, err)
		}
	}
}
