const fs = require('fs');

const path = 'lib/auth/workspace-auth.ts';
let content = fs.readFileSync(path, 'utf8');

const replacement = `if (!principal) {
      if (isDevBypass) {
        const userRow = await queryOne<{ id: string }>(
          \`SELECT id FROM fs_users WHERE data->>'email' = $1 LIMIT 1\`,
          [process.env.NEXT_PUBLIC_DEV_LOCAL_AUTH_EMAIL]
        );
        if (userRow) {
          const workspace = await getWorkspaceByOwner(userRow.id);
          if (workspace) {
            return { source: 'api_key', workspace, userId: userRow.id, apiKeyId: 'dev_bypass' };
          }
        }
      }
      return NextResponse.json({ error: 'Invalid or revoked API key' }, { status: 401 });
    }
    if (!matchesTarget(principal.workspace, opts)) {
      return NextResponse.json({ error: 'API key not authorized for this workspace' }, { status: 403 });
    }
    return principal;
  }`;

content = content.replace(
  /if \(\!principal && !isDevBypass\) \{[\s\S]*?return principal;\n    \}\n  \}/m,
  replacement
);

fs.writeFileSync(path, content);
