package auth

import (
	"context"
	"database/sql"
	"fmt"
	"time"

	"hyapp/pkg/appcode"
)

const firstDisplayUserID int64 = 163000

// AllocateDisplayUserID 从数据库序列分配当前 App 下的默认短号。
// 这里不用内存计数，避免服务重启后从 163000 重新发号导致连续冲突。
func (r *Repository) AllocateDisplayUserID(ctx context.Context, appCode string) (string, error) {
	tx, err := r.db.BeginTx(ctx, nil)
	if err != nil {
		return "", err
	}
	defer tx.Rollback()

	normalized := appcode.Normalize(appCode)
	var next int64
	err = tx.QueryRowContext(ctx, `
		SELECT next_value
		FROM display_user_id_sequences
		WHERE app_code = ?
		FOR UPDATE
	`, normalized).Scan(&next)
	if err == sql.ErrNoRows {
		next = firstDisplayUserID
		_, err = tx.ExecContext(ctx, `
			INSERT INTO display_user_id_sequences (app_code, next_value, updated_at_ms)
			VALUES (?, ?, ?)
		`, normalized, next+1, time.Now().UTC().UnixMilli())
	} else if err == nil {
		_, err = tx.ExecContext(ctx, `
			UPDATE display_user_id_sequences
			SET next_value = ?, updated_at_ms = ?
			WHERE app_code = ?
		`, next+1, time.Now().UTC().UnixMilli(), normalized)
	}
	if err != nil {
		return "", err
	}
	if err := tx.Commit(); err != nil {
		return "", err
	}

	return fmt.Sprintf("%d", next), nil
}
