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

/**
 * DevTools controller for TypedServer
 * Handles /typedserver/devtools and /typedserver/reloadcheck endpoints
 */
@plugins.smartserve.Route('/typedserver')
export class DevToolsController {
  private getLastReload: () => number;
  private getEnded: () => boolean;

  constructor(options?: { getLastReload: () => number; getEnded: () => boolean }) {
    // Default no-op functions for when controller is auto-instantiated without options
    this.getLastReload = options?.getLastReload ?? (() => 0);
    this.getEnded = options?.getEnded ?? (() => false);
  }

  @plugins.smartserve.Get('/devtools')
  async getDevtools(ctx: plugins.smartserve.IRequestContext): Promise<Response> {
    const devtoolsContent = (await plugins.fsInstance
      .file(paths.injectBundlePath)
      .encoding('utf8')
      .read()) as string;

    return new Response(devtoolsContent, {
      status: 200,
      headers: {
        'Content-Type': 'text/javascript',
      },
    });
  }

  @plugins.smartserve.Post('/reloadcheck')
  async reloadCheck(ctx: plugins.smartserve.IRequestContext): Promise<Response> {
    console.log('got request for reloadcheck');

    if (this.getEnded()) {
      return new Response('end', {
        status: 200,
        headers: {
          'Content-Type': 'text/plain',
        },
      });
    }

    return new Response(this.getLastReload().toString(), {
      status: 200,
      headers: {
        'Content-Type': 'text/plain',
      },
    });
  }
}
