import * as http from 'http';
import { parse } from 'url';
import { join, extname, normalize } from 'path';
import { createReadStream, statSync } from 'fs';
import next from 'next';
import { loadEnvConfig } from '@next/env';

loadEnvConfig(process.cwd());

const dev = process.env.NODE_ENV !== 'production';
const port = parseInt(process.env.PORT || '5000', 10);

const app = next({ dev, hostname: '0.0.0.0', port });
const handle = app.getRequestHandler();

const MIME_TYPES: Record<string, string> = {
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.gif': 'image/gif',
  '.webp': 'image/webp',
  '.svg': 'image/svg+xml',
  '.ico': 'image/x-icon',
};

function serveUpload(req: http.IncomingMessage, res: http.ServerResponse): boolean {
  const rawUrl = req.url;
  if (!rawUrl || !rawUrl.startsWith('/uploads/')) return false;

  const urlPath = rawUrl.split('?')[0];

  let decoded: string;
  try {
    decoded = decodeURIComponent(urlPath);
  } catch {
    res.writeHead(400);
    res.end('Bad request');
    return true;
  }

  if (decoded.includes('..') || decoded.includes('\0')) {
    res.writeHead(400);
    res.end('Bad request');
    return true;
  }

  const normalized = normalize(decoded);
  if (!normalized.startsWith('/uploads/')) {
    res.writeHead(400);
    res.end('Bad request');
    return true;
  }

  const filePath = join(process.cwd(), 'public', normalized);

  let stat;
  try {
    stat = statSync(filePath);
  } catch {
    res.writeHead(404);
    res.end('Not found');
    return true;
  }
  if (!stat.isFile()) {
    res.writeHead(404);
    res.end('Not found');
    return true;
  }

  const ext = extname(filePath).toLowerCase();
  const contentType = MIME_TYPES[ext] || 'application/octet-stream';

  res.writeHead(200, {
    'Content-Type': contentType,
    'Cache-Control': 'public, max-age=31536000, immutable',
  });
  const stream = createReadStream(filePath);
  stream.on('error', () => {
    if (!res.headersSent) {
      res.writeHead(500);
    }
    res.end();
  });
  stream.pipe(res);
  return true;
}

app.prepare().then(async () => {
  const { engineRegistry } = await import('./src/server/engine/index');

  const server = http.createServer((req, res) => {
    if (serveUpload(req, res)) return;
    const parsedUrl = parse(req.url!, true);
    handle(req, res, parsedUrl);
  });

  engineRegistry.attach(server);

  server.listen(port, '0.0.0.0', () => {
    console.log(`> RestroAgent ready on http://0.0.0.0:${port} [${dev ? 'dev' : 'production'}]`);
  });
}).catch((err) => {
  console.error('Failed to start server:', err);
  process.exit(1);
});
