import {FastifyPluginAsyncTypebox, Type} from '@fastify/type-provider-typebox'
import {handleError} from '../../../utils/errorHandler.js'
import {Ticker} from '../../../generated/ManagingApiTypes.js'

const plugin: FastifyPluginAsyncTypebox = async (fastify) => {
  fastify.post(
    '/sign-message',
    {
      schema: {
        body: Type.Object({
          walletId: Type.String(),
          message: Type.String(),
          address: Type.String()
        }),
        response: {
          200: Type.Object({
            success: Type.Boolean(),
            signature: Type.Optional(Type.String()),
            error: Type.Optional(Type.String())
          }),
          400: Type.Object({
            success: Type.Boolean(),
            error: Type.String()
          }),
          500: Type.Object({
            success: Type.Boolean(),
            error: Type.String()
          })
        },
        tags: ['Privy']
      }
    },
    async function (request, reply) {
      try {
        const { walletId, message, address } = request.body;
        return await request.signPrivyMessage(reply, walletId, message, address);
      } catch (error) {
        return handleError(request, reply, error, 'privy/sign-message');
      }
    }
  )

  fastify.post(
    '/init-address',
    {
      schema: {
        body: Type.Object({
          address: Type.String()
        }),
        response: {
          200: Type.Object({
            success: Type.Boolean(),
            usdcHash: Type.Optional(Type.String()),
            orderVaultHash: Type.Optional(Type.String()),
            exchangeRouterHash: Type.Optional(Type.String()),
            error: Type.Optional(Type.String())
          }),
          400: Type.Object({
            success: Type.Boolean(),
            error: Type.String()
          }),
          500: Type.Object({
            success: Type.Boolean(),
            error: Type.String()
          })
        },
        tags: ['Privy']
      }
    },
    async function (request, reply) {
      try {
        const { address } = request.body;
        return await request.initAddress(reply, address);
      } catch (error) {
        return handleError(request, reply, error, 'privy/init-address');
      }
    }
  )

  fastify.post(
    '/send-token',
    {
      schema: {
        body: Type.Object({
          senderAddress: Type.String(),
          recipientAddress: Type.String(),
          ticker: Type.String(),
          amount: Type.String(), // Using string for bigint compatibility
          chainId: Type.Optional(Type.Number())
        }),
        response: {
          200: Type.Object({
            success: Type.Boolean(),
            hash: Type.Optional(Type.String()),
            error: Type.Optional(Type.String())
          }),
          400: Type.Object({
            success: Type.Boolean(),
            error: Type.String()
          }),
          500: Type.Object({
            success: Type.Boolean(),
            error: Type.String()
          })
        },
        tags: ['Privy']
      }
    },
    async function (request, reply) {
      try {
        const { senderAddress, recipientAddress, ticker, amount, chainId } = request.body;
        
        // Pass amount directly to sendTokenImpl - it will handle decimal conversion internally
        return await request.sendToken(reply, senderAddress, recipientAddress, ticker, amount, chainId);
      } catch (error) {
        return handleError(request, reply, error, 'privy/send-token');
      }
    }
  )

  fastify.get(
    '/wallet-balance',
    {
      schema: {
        querystring: Type.Object({
          address: Type.String(),
          asset: Type.Union([Type.String(), Type.Array(Type.String())]), // Can be single or array
          chain: Type.Union([Type.String(), Type.Array(Type.String())]) // Can be single or array
        }),
        response: {
          200: Type.Object({
            success: Type.Boolean(),
            balances: Type.Optional(Type.Array(Type.Object({
              tokenImage: Type.Optional(Type.String()),
              tokenName: Type.Optional(Type.String()),
              amount: Type.Optional(Type.Number()),
              price: Type.Optional(Type.Number()),
              value: Type.Optional(Type.Number()),
              tokenAdress: Type.Optional(Type.String()),
              chain: Type.Optional(Type.Object({
                id: Type.Optional(Type.String()),
                rpcUrl: Type.Optional(Type.String()),
                name: Type.Optional(Type.String()),
                chainId: Type.Optional(Type.Number())
              }))
            }))),
            error: Type.Optional(Type.String())
          }),
          400: Type.Object({
            success: Type.Boolean(),
            error: Type.String()
          }),
          500: Type.Object({
            success: Type.Boolean(),
            error: Type.String()
          })
        },
        tags: ['Privy']
      }
    },
    async function (request, reply) {
      try {
        const { address, asset, chain } = request.query;
        
        // Convert single values to arrays if needed
        const assetsArray = Array.isArray(asset) ? asset : [asset];
        const chainsArray = Array.isArray(chain) ? chain : [chain];
        
        // Convert asset strings to Ticker enums
        const assetEnums = assetsArray.map(a => a as Ticker);
        
        return await request.getWalletBalance(reply, address, assetEnums, chainsArray);
      } catch (error) {
        return handleError(request, reply, error, 'privy/wallet-balance');
      }
    }
  )
}

export default plugin 