package mysql

import (
	"context"
	"database/sql"
	"errors"
	"strings"

	_ "github.com/go-sql-driver/mysql"
	"hyapp/pkg/appcode"
	"hyapp/pkg/xerr"
	activitydomain "hyapp/services/activity-service/internal/domain/activity"
)

// Repository 是 activity-service 的 MySQL 存储入口。
type Repository struct {
	db *sql.DB
}

// Open 创建 MySQL 连接池并做启动 ping。
func Open(ctx context.Context, dsn string) (*Repository, error) {
	if strings.TrimSpace(dsn) == "" {
		return nil, xerr.New(xerr.InvalidArgument, "mysql_dsn is required")
	}

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return nil, err
	}

	if err := db.PingContext(ctx); err != nil {
		_ = db.Close()
		return nil, err
	}

	return &Repository{db: db}, nil
}

// Close 释放 MySQL 连接池。
func (r *Repository) Close() error {
	if r == nil || r.db == nil {
		return nil
	}

	return r.db.Close()
}

// Ping 验证 MySQL 当前可用。
func (r *Repository) Ping(ctx context.Context) error {
	if r == nil || r.db == nil {
		return xerr.New(xerr.Unavailable, "mysql repository is not configured")
	}

	return r.db.PingContext(ctx)
}

// GetActivity 从 MySQL 活动配置表读取同步查询投影。
func (r *Repository) GetActivity(ctx context.Context, activityID string) (activitydomain.Activity, error) {
	if r == nil || r.db == nil {
		return activitydomain.Activity{}, xerr.New(xerr.Unavailable, "mysql repository is not configured")
	}

	row := r.db.QueryRowContext(ctx,
		`SELECT app_code, activity_id, status, updated_at_ms
		 FROM activities
		 WHERE app_code = ? AND activity_id = ?`,
		appcode.FromContext(ctx),
		activityID,
	)

	var activity activitydomain.Activity
	var status string
	if err := row.Scan(&activity.AppCode, &activity.ActivityID, &status, &activity.UpdatedAtMs); err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			// 未配置活动时返回 NotFound，上层可决定是否降级为 inactive。
			return activitydomain.Activity{}, xerr.New(xerr.NotFound, "activity not found")
		}

		return activitydomain.Activity{}, err
	}
	activity.Status = activitydomain.Status(status)

	return activity, nil
}
