import {FastifyPluginAsyncTypebox, Type} from '@fastify/type-provider-typebox'
import { handleError } from '../../../utils/errorHandler.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');
      }
    }
  )
}

export default plugin 