package coredb

import (
	"context"
	"crypto/sha1"
	"database/sql"
	"errors"
	"fmt"
	"strings"
	"time"
)

const (
	systemBootstrapLockID         int64         = 0x636839626f6f74
	systemBootstrapLockName                     = "agentteam_system_bootstrap"
	systemBootstrapLockWait       time.Duration = 15 * time.Second
	systemBootstrapReleaseTimeout               = 5 * time.Second
)

// AcquireSystemBootstrapLock serializes one-time system bootstrap on an
// existing TiDB transaction without relying on a migration state table.
func AcquireSystemBootstrapLock(ctx context.Context, tx Tx) (func(context.Context) error, error) {
	switch typed := tx.(type) {
	case *sqlTxAdapter, *sqlxTx:
		return acquireTiDBSystemBootstrapLock(ctx, typed)
	default:
		if IsTiDB(typed) {
			return acquireTiDBSystemBootstrapLock(ctx, typed)
		}
		return nil, fmt.Errorf("bootstrap lock is not implemented for %T", tx)
	}
}

// WithSystemBootstrapLockTx runs fn inside a transaction protected by the
// system bootstrap advisory lock on one pinned TiDB session.
func WithSystemBootstrapLockTx(ctx context.Context, db DB, fn func(Tx) error) (err error) {
	if db == nil {
		return fmt.Errorf("coredb db is nil")
	}
	if fn == nil {
		return fmt.Errorf("coredb bootstrap tx function is nil")
	}
	if ctx == nil {
		ctx = context.Background()
	}
	if runner, ok := db.(systemBootstrapLockTxRunner); ok {
		return runner.WithSystemBootstrapLockTx(ctx, fn)
	}
	sqlDB := RawSQLDB(db)
	if sqlDB == nil || !IsTiDB(db) {
		return fmt.Errorf("system bootstrap lock requires a tidb sql db")
	}

	conn, err := sqlDB.Conn(ctx)
	if err != nil {
		return fmt.Errorf("pin tidb bootstrap session: %w", err)
	}
	defer func() {
		if closeErr := conn.Close(); closeErr != nil && err == nil {
			err = fmt.Errorf("close tidb bootstrap session: %w", closeErr)
		}
	}()

	session := &sqlConnAdapter{conn: conn}
	release, err := acquireTiDBSystemBootstrapLock(ctx, session)
	if err != nil {
		return err
	}
	defer func() {
		releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), systemBootstrapReleaseTimeout)
		defer cancel()
		releaseErr := release(releaseCtx)
		if recovered := recover(); recovered != nil {
			panic(recovered)
		}
		err = errors.Join(err, releaseErr)
	}()

	return WithTx(ctx, session, fn)
}

type systemBootstrapLockTxRunner interface {
	WithSystemBootstrapLockTx(context.Context, func(Tx) error) error
}

func acquireTiDBSystemBootstrapLock(ctx context.Context, db Queryer) (func(context.Context) error, error) {
	lockName, err := systemBootstrapLockNameForQueryer(ctx, db)
	if err != nil {
		return nil, err
	}

	timeoutSeconds := int(systemBootstrapLockWait / time.Second)
	if timeoutSeconds <= 0 {
		timeoutSeconds = 1
	}

	var acquired sql.NullInt64
	deadline := time.Now().Add(systemBootstrapLockWait)
	for {
		if err := db.QueryRow(ctx, `SELECT GET_LOCK(?, ?)`, lockName, timeoutSeconds).Scan(&acquired); err != nil {
			if !isTiDBBootstrapLockRetryable(err) || !time.Now().Before(deadline) {
				return nil, fmt.Errorf("acquire tidb bootstrap lock: %w", err)
			}
			select {
			case <-ctx.Done():
				return nil, fmt.Errorf("acquire tidb bootstrap lock: %w", ctx.Err())
			case <-time.After(50 * time.Millisecond):
				continue
			}
		}
		break
	}
	if err := validateTiDBBootstrapLockAcquired(acquired); err != nil {
		return nil, err
	}

	return func(releaseCtx context.Context) error {
		var released sql.NullInt64
		if err := db.QueryRow(releaseCtx, `SELECT RELEASE_LOCK(?)`, lockName).Scan(&released); err != nil {
			return fmt.Errorf("release tidb bootstrap lock: %w", err)
		}
		if !released.Valid {
			return fmt.Errorf("release tidb bootstrap lock: returned NULL")
		}
		if released.Int64 != 1 {
			return fmt.Errorf("release tidb bootstrap lock: current session did not release lock (result %d)", released.Int64)
		}
		return nil
	}, nil
}

func validateTiDBBootstrapLockAcquired(acquired sql.NullInt64) error {
	if !acquired.Valid {
		return fmt.Errorf("acquire tidb bootstrap lock: returned NULL")
	}
	switch acquired.Int64 {
	case 1:
		return nil
	case 0:
		return fmt.Errorf("acquire tidb bootstrap lock: timed out")
	default:
		return fmt.Errorf("acquire tidb bootstrap lock: unexpected result %d", acquired.Int64)
	}
}

func isTiDBBootstrapLockRetryable(err error) bool {
	message := strings.ToLower(err.Error())
	return strings.Contains(message, "pessimistic lock retry limit reached") ||
		strings.Contains(message, "write conflict")
}

func systemBootstrapLockNameForQueryer(ctx context.Context, db Queryer) (string, error) {
	var databaseName sql.NullString
	if err := db.QueryRow(ctx, `SELECT DATABASE()`).Scan(&databaseName); err != nil {
		return "", fmt.Errorf("detect current database for bootstrap lock: %w", err)
	}

	trimmedDatabaseName := strings.TrimSpace(databaseName.String)
	if trimmedDatabaseName == "" {
		return systemBootstrapLockName, nil
	}

	lockName := systemBootstrapLockName + ":" + trimmedDatabaseName
	if len(lockName) <= 64 {
		return lockName, nil
	}

	sum := sha1.Sum([]byte(trimmedDatabaseName))
	return fmt.Sprintf("%s:%x", systemBootstrapLockName, sum[:8]), nil
}
