package mtproto

import (
	
	

	
	
)

var (
	// ErrPFSReconnectRequired is returned when connection should be recreated
	// to continue PFS flow (e.g. temp key renewal).
	ErrPFSReconnectRequired = errors.New("pfs reconnect required")
	// ErrPFSDropKeysRequired is returned when stored permanent key should be
	// dropped and generated again on the next connection attempt.
	ErrPFSDropKeysRequired = errors.New("pfs drop keys required")
)

func ( *Conn) ( context.Context) error {
	if !.pfs {
		<-.Done()
		return .Err()
	}

	for {
		.sessionMux.RLock()
		 := .tempKeyExpiry
		.sessionMux.RUnlock()
		if  == 0 {
			// If expiry was not recorded (e.g. restored runtime state), derive
			// a conservative local horizon from configured ttl.
			 = .clock.Now().Unix() + int64(.tempKeyTTL)
		}

		// Reconnect after 75% of ttl to leave buffer for bind retries.
		 :=  - int64(.tempKeyTTL)/4
		 := time.Unix(, 0).Sub(.clock.Now())
		if  < 0 {
			 = 0
		}

		 := .clock.Timer()
		select {
		case <-.Done():
			.Stop()
			return .Err()
		case <-.C():
		}
		.log.Info(, "Temporary auth key renewal required, reconnecting",
			log.Int64("expires_at", ),
			log.Int64("renew_at", ),
		)
		return errors.Wrap(ErrPFSReconnectRequired, "temporary auth key renewal required")
	}
}