import express, { Application } from 'express';
import cors from 'cors';
import { config } from 'dotenv';
import { Config } from './types/api';

// Load environment variables
config();

// Application configuration
export const appConfig: Config = {
  port: parseInt(process.env.PORT || '3000'),
  geminiApiKey: process.env.GEMINI_API_KEY || '',
  resultsDir: './src/results',
  uploadsDir: './uploads/temp',
  maxFileSize: 5 * 1024 * 1024, // 5MB
  maxFiles: 3
};

// Create Express application
export const createApp = (): Application => {
  const app = express();

  // Middleware
  app.use(cors({
    origin: process.env.CORS_ORIGIN || '*',
    credentials: true
  }));

  app.use(express.json({ limit: '10mb' }));
  app.use(express.urlencoded({ extended: true, limit: '10mb' }));

  // Request ID middleware for logging
  app.use((req, res, next) => {
    req.requestId = Math.random().toString(36).substr(2, 9);
    res.setHeader('X-Request-ID', req.requestId);
    next();
  });

  // Health check endpoint
  app.get('/health', (req, res) => {
    const health = {
      status: 'healthy',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
      environment: process.env.NODE_ENV || 'development',
      version: process.env.npm_package_version || '1.0.0'
    };

    console.log(`[${health.timestamp}] Health check - ${health.status}`);
    res.json(health);
  });

  // API info endpoint
  app.get('/api/info', (req, res) => {
    const info = {
      name: 'Magic Building Image Generation API',
      version: '1.0.0',
      description: 'Express.js server for Gemini AI image generation',
      endpoints: {
        'GET /health': 'Health check',
        'GET /api/info': 'API information',
        'POST /api/generate': 'Generate images from text prompt with optional reference images'
      },
      limits: {
        maxFileSize: `${appConfig.maxFileSize / (1024 * 1024)}MB`,
        maxFiles: appConfig.maxFiles,
        supportedFormats: ['PNG', 'JPEG', 'JPG', 'WebP']
      }
    };

    console.log(`[${new Date().toISOString()}] API info requested`);
    res.json(info);
  });

  return app;
};

// Extend Express Request type to include requestId
declare global {
  namespace Express {
    interface Request {
      requestId: string;
    }
  }
}