import express, { Application } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import path from 'path';
import fs from 'fs';
import yaml from 'js-yaml';
import { errorHandler } from './middleware/error.middleware';
import { requestLogger } from './middleware/request-logger.middleware';
import routes from './routes';

const app: Application = express();

// Security middleware
app.use(helmet({
  contentSecurityPolicy: false, // Allow ReDoc to load
}));
app.use(cors());

// Body parsing
app.use(express.json());

// Request logging
app.use(requestLogger);

// API Documentation - ReDoc
app.get('/docs', (_req, res) => {
  res.send(`
<!DOCTYPE html>
<html>
  <head>
    <title>SportPulse Widget API - Documentation</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
    <style>
      body { margin: 0; padding: 0; }
    </style>
  </head>
  <body>
    <redoc spec-url="/openapi.json"></redoc>
    <script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
  </body>
</html>
  `);
});

// Serve OpenAPI spec as JSON
app.get('/openapi.json', (_req, res) => {
  try {
    const openapiPath = path.join(process.cwd(), 'openapi.yaml');
    const openapiContent = fs.readFileSync(openapiPath, 'utf-8');
    const openapiJson = yaml.load(openapiContent);
    res.json(openapiJson);
  } catch (error) {
    res.status(500).json({ error: 'Failed to load OpenAPI spec' });
  }
});

// Serve OpenAPI spec as YAML
app.get('/openapi.yaml', (_req, res) => {
  try {
    const openapiPath = path.join(process.cwd(), 'openapi.yaml');
    res.type('text/yaml').sendFile(openapiPath);
  } catch (error) {
    res.status(500).json({ error: 'Failed to load OpenAPI spec' });
  }
});

// API routes
app.use('/api/v1', routes);

// Health check
app.get('/health', (_req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// Error handling
app.use(errorHandler);

export default app;
