/**
 * Main Entry Point
 * Mecánicas Diesel Backend - ERP Suite
 */

import 'reflect-metadata';
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import morgan from 'morgan';
import { config } from 'dotenv';
import { DataSource } from 'typeorm';

// Controllers
import { createAuthController } from './modules/auth/auth.controller';
import { createUsersController } from './modules/users/users.controller';
import { createServiceOrderController } from './modules/service-management/controllers/service-order.controller';
import { createQuoteController } from './modules/service-management/controllers/quote.controller';
import { createDiagnosticController } from './modules/service-management/controllers/diagnostic.controller';
import { createVehicleController } from './modules/vehicle-management/controllers/vehicle.controller';
import { createFleetController } from './modules/vehicle-management/controllers/fleet.controller';
import { createPartController } from './modules/parts-management/controllers/part.controller';
import { createSupplierController } from './modules/parts-management/controllers/supplier.controller';
import { createCustomersRouter } from './modules/customers/controllers/customers.controller';

// Entities - Auth
import { User } from './modules/auth/entities/user.entity';
import { RefreshToken } from './modules/auth/entities/refresh-token.entity';
import { Workshop } from './modules/auth/entities/workshop.entity';

// Entities - Service Management
import { ServiceOrder } from './modules/service-management/entities/service-order.entity';
import { OrderItem } from './modules/service-management/entities/order-item.entity';
import { Diagnostic } from './modules/service-management/entities/diagnostic.entity';
import { Quote } from './modules/service-management/entities/quote.entity';
import { WorkBay } from './modules/service-management/entities/work-bay.entity';
import { Service } from './modules/service-management/entities/service.entity';
import { Vehicle } from './modules/vehicle-management/entities/vehicle.entity';
import { Fleet } from './modules/vehicle-management/entities/fleet.entity';
import { VehicleEngine } from './modules/vehicle-management/entities/vehicle-engine.entity';
import { EngineCatalog } from './modules/vehicle-management/entities/engine-catalog.entity';
import { MaintenanceReminder } from './modules/vehicle-management/entities/maintenance-reminder.entity';
import { Part } from './modules/parts-management/entities/part.entity';
import { PartCategory } from './modules/parts-management/entities/part-category.entity';
import { Supplier } from './modules/parts-management/entities/supplier.entity';
import { WarehouseLocation } from './modules/parts-management/entities/warehouse-location.entity';

// Entities - Customers
import { Customer } from './modules/customers/entities/customer.entity';

// Load environment variables
config();

const app = express();
const PORT = process.env.PORT || 3011;

// Database configuration
const AppDataSource = new DataSource({
  type: 'postgres',
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT || '5432', 10),
  username: process.env.DB_USER || 'postgres',
  password: process.env.DB_PASSWORD || 'postgres',
  database: process.env.DB_NAME || 'mecanicas_diesel',
  schema: process.env.DB_SCHEMA || 'public',
  entities: [
    // Auth
    User,
    RefreshToken,
    Workshop,
    // Service Management
    ServiceOrder,
    OrderItem,
    Diagnostic,
    Quote,
    WorkBay,
    Service,
    // Vehicle Management
    Vehicle,
    Fleet,
    VehicleEngine,
    EngineCatalog,
    MaintenanceReminder,
    // Parts Management
    Part,
    PartCategory,
    Supplier,
    WarehouseLocation,
    // Customers
    Customer,
  ],
  synchronize: process.env.NODE_ENV === 'development',
  logging: process.env.NODE_ENV === 'development',
});

// Middleware
app.use(helmet());
app.use(cors({
  origin: process.env.CORS_ORIGINS?.split(',') || ['http://localhost:3000', 'http://localhost:5175'],
  credentials: true,
}));
app.use(compression());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan(process.env.NODE_ENV === 'production' ? 'combined' : 'dev'));

// Health check
app.get('/health', (_req, res) => {
  res.json({
    status: 'healthy',
    service: 'mecanicas-diesel-backend',
    version: '0.1.0',
    timestamp: new Date().toISOString(),
    database: AppDataSource.isInitialized ? 'connected' : 'disconnected',
  });
});

// Initialize database and routes
async function bootstrap() {
  try {
    // Initialize database connection
    await AppDataSource.initialize();
    console.log('📦 Database connection established');

    // Register API routes
    app.use('/api/v1/auth', createAuthController(AppDataSource));
    app.use('/api/v1/users', createUsersController(AppDataSource));
    app.use('/api/v1/service-orders', createServiceOrderController(AppDataSource));
    app.use('/api/v1/quotes', createQuoteController(AppDataSource));
    app.use('/api/v1/diagnostics', createDiagnosticController(AppDataSource));
    app.use('/api/v1/vehicles', createVehicleController(AppDataSource));
    app.use('/api/v1/fleets', createFleetController(AppDataSource));
    app.use('/api/v1/parts', createPartController(AppDataSource));
    app.use('/api/v1/suppliers', createSupplierController(AppDataSource));
    app.use('/api/v1/customers', createCustomersRouter(AppDataSource));

    // API documentation endpoint
    app.get('/api/v1', (_req, res) => {
      res.json({
        name: 'Mecánicas Diesel API',
        version: '1.0.0',
        endpoints: {
          auth: '/api/v1/auth',
          users: '/api/v1/users',
          customers: '/api/v1/customers',
          serviceOrders: '/api/v1/service-orders',
          quotes: '/api/v1/quotes',
          diagnostics: '/api/v1/diagnostics',
          vehicles: '/api/v1/vehicles',
          fleets: '/api/v1/fleets',
          parts: '/api/v1/parts',
          suppliers: '/api/v1/suppliers',
        },
        documentation: '/api/v1/docs',
      });
    });

    // 404 handler
    app.use((_req, res) => {
      res.status(404).json({ error: 'Not Found' });
    });

    // Error handler
    app.use((err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
      console.error(err.stack);
      res.status(500).json({
        error: 'Internal Server Error',
        message: process.env.NODE_ENV === 'development' ? err.message : undefined,
      });
    });

    // Start server
    app.listen(PORT, () => {
      console.log(`🔧 Mecánicas Diesel Backend running on port ${PORT}`);
      console.log(`📊 Environment: ${process.env.NODE_ENV || 'development'}`);
      console.log(`🏥 Health check: http://localhost:${PORT}/health`);
      console.log(`📚 API Root: http://localhost:${PORT}/api/v1`);
    });
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
}

bootstrap();
