import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError, ValidationError } from '@server/errors';
import { readEnvFile, setEnvVar, triggerDevRestart, isDevRestartSupported } from '@server/lib/envFile';

const KEY = 'NEXT_PUBLIC_DEMO_MODE';

function requireAdmin(req: AuthedRequest) {
  if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
    throw new ForbiddenError();
  }
}

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    requireAdmin(req);
    const env = await readEnvFile();
    const value = env[KEY] ?? '';
    return NextResponse.json({
      enabled: value === 'on',
      value,
      writable: process.env.DISABLE_ENV_WRITE !== '1',
    });
  })
);

export const PUT = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    requireAdmin(req);
    if (process.env.DISABLE_ENV_WRITE === '1') {
      return NextResponse.json(
        { error: 'Editing the .env file is disabled on this deployment.', code: 'ENV_WRITE_DISABLED' },
        { status: 403 }
      );
    }
    const body = (await req.json().catch(() => null)) as { enabled?: unknown } | null;
    if (!body || typeof body.enabled !== 'boolean') {
      throw new ValidationError('Body must be { enabled: boolean }');
    }
    const next = body.enabled ? 'on' : 'off';
    await setEnvVar(KEY, next);

    if (isDevRestartSupported()) {
      // Defer the sentinel touch until after this response has been
      // constructed and handed back to Next, so tsx watch doesn't
      // re-exec the process mid-flush and drop the response.
      setImmediate(() => {
        void triggerDevRestart();
      });
      return NextResponse.json({
        ok: true,
        enabled: body.enabled,
        value: next,
        restartRequired: true,
        restartScheduled: true,
        restartEtaMs: 4000,
      });
    }

    return NextResponse.json({
      ok: true,
      enabled: body.enabled,
      value: next,
      restartRequired: true,
      restartScheduled: false,
    });
  })
);
