// Package mysqltest provides real activity-service MySQL repositories for tests.
package mysqltest

import (
	"context"
	"testing"
	"time"

	"hyapp/internal/testutil/mysqlschema"
	activitydomain "hyapp/services/activity-service/internal/domain/activity"
	mysqlstorage "hyapp/services/activity-service/internal/storage/mysql"
)

// Repository wraps the production activity MySQL repository with test seed helpers.
type Repository struct {
	*mysqlstorage.Repository

	t      testing.TB
	schema *mysqlschema.Schema
}

// NewRepository creates an isolated activity schema and opens the production repository.
func NewRepository(t testing.TB) *Repository {
	t.Helper()

	schema := mysqlschema.New(t, mysqlschema.Config{
		EnvVar:         "ACTIVITY_SERVICE_MYSQL_TEST_DSN",
		InitDBPath:     initDBPath(t),
		DatabasePrefix: "hyapp_activity_test",
	})
	repository, err := mysqlstorage.Open(context.Background(), schema.DSN)
	if err != nil {
		t.Fatalf("open activity mysql repository failed: %v", err)
	}

	wrapped := &Repository{Repository: repository, t: t, schema: schema}
	t.Cleanup(wrapped.Close)
	return wrapped
}

// Close shuts down the repository; mysqlschema owns schema cleanup.
func (r *Repository) Close() {
	r.t.Helper()

	if r.Repository != nil {
		_ = r.Repository.Close()
	}
}

// PutActivity seeds one activity projection row.
func (r *Repository) PutActivity(activity activitydomain.Activity) {
	r.t.Helper()

	nowMs := activity.UpdatedAtMs
	if nowMs == 0 {
		nowMs = time.Now().UnixMilli()
	}
	_, err := r.schema.DB.ExecContext(context.Background(), `
		INSERT INTO activities (activity_id, status, updated_at_ms)
		VALUES (?, ?, ?)
		ON DUPLICATE KEY UPDATE
			status = VALUES(status),
			updated_at_ms = VALUES(updated_at_ms)
	`, activity.ActivityID, string(activity.Status), nowMs)
	if err != nil {
		r.t.Fatalf("seed activity failed: %v", err)
	}
}

func initDBPath(t testing.TB) string {
	t.Helper()

	return mysqlschema.InitDBPath(t,
		mysqlschema.CallerFile(t, 1),
		"..", "..", "..", "deploy", "mysql", "initdb", "001_activity_service.sql",
	)
}
