import * as plugins from '../plugins.js';

/**
 * TypedRequest controller for type-safe RPC endpoint
 */
@plugins.smartserve.Route('/typedrequest')
export class TypedRequestController {
  private typedRouter: plugins.typedrequest.TypedRouter;

  constructor(typedRouter: plugins.typedrequest.TypedRouter) {
    this.typedRouter = typedRouter;
  }

  @plugins.smartserve.Post('')
  async handleTypedRequest(ctx: plugins.smartserve.IRequestContext): Promise<Response> {
    try {
      const body = await ctx.json() as plugins.typedrequestInterfaces.ITypedRequest;
      const response = await this.typedRouter.routeAndAddResponse(body);

      return new Response(plugins.smartjson.stringify(response), {
        status: 200,
        headers: {
          'Content-Type': 'application/json',
        },
      });
    } catch (error) {
      return new Response(JSON.stringify({ error: 'Invalid request' }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json',
        },
      });
    }
  }

  @plugins.smartserve.Head('')
  async handleTypedRequestHead(): Promise<Response> {
    // HEAD request for online checking from service worker
    return new Response(null, {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
      },
    });
  }
}
