import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import type { AuthManager } from './auth.js';
import type { CmuxClient } from '../bridge/cmux-client.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export function createApp(auth: AuthManager, cmux: CmuxClient): express.Express {
  const app = express();

  // Security headers
  app.use(auth.cspMiddleware());

  // Parse JSON bodies
  app.use(express.json());

  // Auth status endpoint
  app.get('/api/auth/status', (_req, res) => {
    res.json({ authRequired: !auth.isAuthDisabled() });
  });

  // Auth endpoint
  app.post('/api/auth/login', auth.loginHandler());

  // Claude Code surface detection
  app.get('/api/claude-surfaces', async (_req, res) => {
    try {
      const surfaces = await cmux.getClaudeCodeSurfaceRefs();
      res.json({ surfaces });
    } catch {
      res.json({ surfaces: [] });
    }
  });

  // Codex CLI surface detection
  app.get('/api/codex-surfaces', async (_req, res) => {
    try {
      const surfaces = await cmux.getCodexSurfaceRefs();
      res.json({ surfaces });
    } catch {
      res.json({ surfaces: [] });
    }
  });

  // Token verification endpoint
  app.get('/api/auth/verify', (req, res) => {
    if (auth.isAuthDisabled()) {
      res.json({ valid: true });
      return;
    }
    const authHeader = req.headers.authorization;
    if (!authHeader?.startsWith('Bearer ')) {
      res.status(401).json({ valid: false });
      return;
    }
    const token = authHeader.slice(7);
    const valid = auth.verifyToken(token);
    res.json({ valid });
  });

  // Static files — no-cache so changes are always picked up
  const publicDir = join(__dirname, '..', '..', 'public');
  app.use(express.static(publicDir, {
    setHeaders: (res) => {
      res.setHeader('Cache-Control', 'no-store');
    },
  }));

  // SPA fallback — serve index.html for non-API, non-file routes
  app.get('/{*splat}', (_req, res) => {
    res.setHeader('Cache-Control', 'no-store');
    res.sendFile(join(publicDir, 'index.html'));
  });

  return app;
}
