import {
  Connection,
  PublicKey,
  Transaction,
  sendAndConfirmTransaction,
  Keypair,
  SystemProgram,
} from '@solana/web3.js'
import { ref } from 'vue'

export class SolanaService {
  private connection: Connection
  public wallet = ref(null)

  constructor() {
    this.connection = new Connection('https://app.devnet.solana.com', 'confirmed')
  }

  async createWallet(): Promise<string> {
    this.wallet.value = Keypair.generate()
    return this.wallet.value.publicKey.toString()
  }

  async getBalance(publicKey: string): Promise<number> {
    const balance = await this.connection.getBalance(new PublicKey(publicKey))
    return balance / 1e9 // Convert lamports to SOL
  }

  async sendTransaction(toPublicKey: string, amount: number): Promise<string> {
    if (!this.wallet.value) throw new Error('Wallet not initialized')

    const transaction = new Transaction().add(
      SystemProgram.transfer({
        fromPubkey: this.wallet.value.publicKey,
        toPubkey: new PublicKey(toPublicKey),
        lamports: amount * 1e9, // Convert SOL to lamports
      }),
    )

    const signature = await sendAndConfirmTransaction(this.connection, transaction, [
      this.wallet.value,
    ])

    return signature
  }
}

export const solanaService = new SolanaService()
