"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const body_parser_1 = __importDefault(require("body-parser"));
const cors_1 = __importDefault(require("cors"));
const dotenv_1 = __importDefault(require("dotenv"));
dotenv_1.default.config();
const routes_1 = __importDefault(require("./routes"));
const compression_1 = __importDefault(require("compression"));
const express_useragent_1 = __importDefault(require("express-useragent"));
const main_1 = require("./jobs/main");
const helmet_1 = __importDefault(require("helmet"));
const swagger_ui_express_1 = __importDefault(require("swagger-ui-express"));
const swagger_1 = require("./docs/swagger");
const rateLimite_1 = require("./middleware/rateLimite");
const socket = __importStar(require("./socket"));
const cookie_parser_1 = __importDefault(require("cookie-parser"));
const prisma_1 = require("./database/prisma");
const app = (0, express_1.default)();
const port = process.env.PORT || 8080;
// Nginx, Vercel, Heroku usam proxies que econdem IP real do cliente, a configuracao abaixo
// para obter o IP real do cliente e aplicar o rateLimite corretamente
app.set('trust proxy', 1);
app.use((0, cookie_parser_1.default)());
app.use((0, helmet_1.default)());
app.use((0, compression_1.default)());
app.use((0, cors_1.default)());
app.use(rateLimite_1.globalRateLimit); // Global rateLimite define o limite de requisicao: 200 req / 15 min
// app.use('/images', express.static(path.join(__dirname, 'uploads')));
app.use(body_parser_1.default.json());
app.use(express_useragent_1.default.express());
// Rotas
app.use(routes_1.default);
// Swagger Documentatio
app.use('/docs', swagger_ui_express_1.default.serve, swagger_ui_express_1.default.setup((0, swagger_1.generateOpenApi)()));
app.get('/', (req, res, next) => {
    res.send('<h1>Bem vindo ao Infrasat Backend</h1>');
});
// MiddleWare de Erro
app.use((error, req, res, next) => {
    let errorMessage = error.message;
    if (!error.statusCode) {
        if (error.status) {
            error.statusCode = error.status;
        }
        else {
            error.statusCode = 500;
        }
        // Adiciona prefixo para diferenciar erros externos (como erros de bibliotecas) dos erros internos do sistema
        errorMessage = `[EXT] ${errorMessage}`;
    }
    res.status(error.statusCode).json({ message: errorMessage });
});
(async () => {
    try {
        await prisma_1.prisma.$connect(); // opcional
        const server = app.listen(port, async () => {
            console.log(`
        🚀  Servidor rodando!
        🔉  Ouvindo na porta ${port}    
        📭  Requisição em http://localhost:${port}
      `);
            console.log('entrou');
            const users = await prisma_1.prisma.user.findMany();
            console.log(users, 'users');
            // Roda todas as funcoes de cron
            (0, main_1.startAllJobs)();
            // Socket IO
            const io = socket.init(server);
        });
    }
    catch (err) {
        console.log(err);
    }
})();
