import express, { Request, Response, NextFunction } from 'express';
import bodyParser from 'body-parser';
import 'reflect-metadata';
import cors from 'cors';
import fs from 'fs';
import http from 'http';
import swaggerUi from 'swagger-ui-express';
import { RegisterRoutes } from './tsoa-auto/routes';
import swaggerJson from './tsoa-auto/swagger.json';
import { AppDataSource } from './data-source';
import { envs } from './utils/envVars';
// import { ValidateError } from 'tsoa';
// import { ResponseError } from './models/res/ResErrors';

AppDataSource.initialize()
  .then(async () => {
    await AppDataSource.runMigrations({ transaction: 'each' });

    const app = express();
    const server = http.createServer(app);

    // Setup CORS
    app.use(cors({
      origin: [
        ...envs.CORS_ALLOWED_ORIGINS,
        'http://localhost:3000',
        'http://localhost:3001',
        'http://localhost:8081',
        'https://chronicpestcontrolagencies.org',
      ]
    }));

    // Ensure upload folders exist
    const uploadDirs = [
      './public/uploads/',
      './public/ecuUploads/',
      './public/bannerUploads/',
      './public/vehicleModelPhoto/',
    ];
    uploadDirs.forEach((dir) => {
      if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
    });

    // Middleware
    app.use(bodyParser.json());
    app.use('/public', express.static('./public'));

    // Swagger UI – comment out until tsoa generates the files
    app.use('/docs', swaggerUi.serve, async (_req: Request, res: Response) => {
      res.send(swaggerUi.generateHTML(swaggerJson));
    });

    RegisterRoutes(app); // Comment out until tsoa generates the routes

    // Start server
    server.listen(envs.PORT, () => {
      console.log(`🚀 Server running at http://localhost:${envs.PORT}`);
      console.log(`📚 Swagger docs will be available at http://localhost:${envs.PORT}/docs after TSOA is set up`);
    });
  })
  .catch((error) => console.error('Database init error:', error));
