// Copyright 2017-2026 @pezkuwi/react-signer authors & contributors
// SPDX-License-Identifier: Apache-2.0

import type { Signer, SignerResult } from '@pezkuwi/api/types';
import type { KeyringPair } from '@pezkuwi/keyring/types';
import type { Registry, SignerPayloadJSON } from '@pezkuwi/types/types';

import { objectSpread } from '@pezkuwi/util';

import { lockAccount } from '../util.js';

let id = 0;

export class AccountSigner implements Signer {
  readonly #keyringPair: KeyringPair;
  readonly #registry: Registry;

  constructor (registry: Registry, keyringPair: KeyringPair) {
    this.#keyringPair = keyringPair;
    this.#registry = registry;
  }

  public async signPayload (payload: SignerPayloadJSON): Promise<SignerResult> {
    return new Promise((resolve): void => {
      const signed = this.#registry.createType('ExtrinsicPayload', payload, { version: payload.version }).sign(this.#keyringPair);

      lockAccount(this.#keyringPair);
      resolve(
        objectSpread({ id: ++id }, signed)
      );
    });
  }
}
