import { IMiddleware, Middleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';
import { isLoopbackAddress, validateRuntimeSecret } from '../../../../comm/runtime-secret.js';

@Middleware()
export class BrowserControlAuthMiddleware implements IMiddleware<Context, NextFunction> {
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      const ip = ctx.ip || (ctx as any).request?.ip || (ctx as any).req?.socket?.remoteAddress;
      if (!isLoopbackAddress(ip)) {
        ctx.status = 403;
        ctx.body = { code: 1003, error: 'Forbidden: only loopback access allowed' };
        return;
      }
      const expected = process.env.NETA_TRAY_SECRET ?? '';
      const actual = ctx.headers['x-neta-control-secret'] as string | undefined;
      const isDev = process.env.NODE_ENV !== 'production';
      if (isDev && !expected) {
        await next();
        return;
      }
      if (!validateRuntimeSecret(expected, actual)) {
        ctx.status = 401;
        ctx.body = { code: 1001, error: 'Unauthorized: invalid x-neta-control-secret' };
        return;
      }
      await next();
    };
  }

  match(ctx: Context): boolean {
    return ctx.path?.startsWith('/admin/browser-daemon/') ?? false;
  }

  static getName(): string {
    return 'browserControlAuth';
  }
}
