// Initialize Firebase Admin SDK first
import './config/firebase';

import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import { config } from './config/env';
import { logger } from './utils/logger';
import documentRoutes from './routes/documents';
import vectorRoutes from './routes/vector';
import monitoringRoutes from './routes/monitoring';

import { errorHandler } from './middleware/errorHandler';
import { notFoundHandler } from './middleware/notFoundHandler';


const app = express();

// Add this middleware to log all incoming requests
app.use((req, res, next) => {
  console.log(`🚀 Incoming request: ${req.method} ${req.path}`);
  console.log(`🚀 Request headers:`, Object.keys(req.headers));
  console.log(`🚀 Request body size:`, req.headers['content-length'] || 'unknown');
  console.log(`🚀 Origin:`, req.headers['origin']);
  console.log(`🚀 User-Agent:`, req.headers['user-agent']);
  next();
});

// Enable trust proxy to ensure Express works correctly behind a proxy
app.set('trust proxy', 1);

// Security middleware
app.use(helmet());

// CORS configuration
const allowedOrigins = [
  'https://cim-summarizer.web.app',
  'https://cim-summarizer.firebaseapp.com',
  'http://localhost:3000',
  'http://localhost:5173'
];

app.use(cors({
  origin: function (origin, callback) {
    console.log(`🌐 CORS check for origin: ${origin}`);
    if (!origin || allowedOrigins.indexOf(origin) !== -1) {
      console.log(`✅ CORS allowed for origin: ${origin}`);
      callback(null, true);
    } else {
      console.log(`❌ CORS blocked for origin: ${origin}`);
      logger.warn(`CORS blocked for origin: ${origin}`);
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
  optionsSuccessStatus: 200
}));

// Rate limiting
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 1000, 
  message: {
    error: 'Too many requests from this IP, please try again later.',
  },
  standardHeaders: true,
  legacyHeaders: false,
});

app.use(limiter);

// Logging middleware
app.use(morgan('combined', {
  stream: {
    write: (message: string) => logger.info(message.trim()),
  },
}));

// CRITICAL: Add body parsing BEFORE routes
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// Health check endpoint
app.get('/health', (_req, res) => {
  res.status(200).json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    environment: config.nodeEnv,
  });
});

// API Routes
app.use('/documents', documentRoutes);
app.use('/vector', vectorRoutes);
app.use('/monitoring', monitoringRoutes);


import * as functions from 'firebase-functions';
import { onRequest } from 'firebase-functions/v2/https';

// API root endpoint
app.get('/', (_req, res) => {
  res.json({
    message: 'CIM Document Processor API',
    version: '1.0.0',
    endpoints: {
      documents: '/documents',
      health: '/health',
      monitoring: '/monitoring',
    },
  });
});

// 404 handler
app.use(notFoundHandler);

// Global error handler (must be last)
app.use(errorHandler);

// Configure Firebase Functions v2 for larger uploads
export const api = onRequest({
  timeoutSeconds: 1800, // 30 minutes (increased from 9 minutes)
  memory: '2GiB',
  cpu: 1,
  maxInstances: 10,
  cors: true
}, app); 