"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const common_1 = require("@nestjs/common");
const core_1 = require("@nestjs/core");
const path_1 = require("path");
const qs = __importStar(require("qs"));
const app_module_1 = require("./app.module");
const config_1 = require("@nestjs/config");
const swagger_1 = require("@nestjs/swagger");
async function bootstrap() {
    const app = await core_1.NestFactory.create(app_module_1.AppModule, {
        logger: ['error', 'warn', 'log', 'debug'],
    });
    app.set('query parser', (str) => qs.parse(str));
    app.useGlobalPipes(new common_1.ValidationPipe({
        whitelist: true,
        transform: true,
    }));
    const configService = app.get(config_1.ConfigService);
    const port = configService.getOrThrow('PORT');
    const nodeEnv = configService.getOrThrow('NODE_ENV');
    const databaseUrl = configService.getOrThrow('DATABASE_URL');
    const jwtSecret = configService.getOrThrow('JWT_SECRET');
    const jwtExpiresIn = configService.getOrThrow('JWT_EXPIRES_IN');
    const clientUrl = configService.getOrThrow('CLIENT_URL');
    console.log('Config verification:');
    console.log('PORT:', port);
    console.log('NODE_ENV:', nodeEnv);
    console.log('DATABASE_URL:', databaseUrl ? '***' : undefined);
    console.log('JWT_SECRET:', jwtSecret ? '***' : undefined);
    console.log('JWT_EXPIRES_IN:', jwtExpiresIn);
    console.log('CLIENT_URL:', clientUrl);
    const allowedOrigins = clientUrl.split(',').map(o => o.trim());
    console.log('CORS allowed:', allowedOrigins);
    function isOriginAllowed(origin) {
        return allowedOrigins.some(pattern => {
            if (pattern === '*')
                return true;
            if (pattern === origin)
                return true;
            if (pattern.startsWith('*.')) {
                const domain = pattern.slice(2);
                return (origin.endsWith(`.${domain}`) ||
                    origin === `https://${domain}` ||
                    origin === `http://${domain}`);
            }
            return false;
        });
    }
    app.enableCors({
        origin: (origin, callback) => {
            if (!origin)
                return callback(null, true);
            if (isOriginAllowed(origin)) {
                return callback(null, true);
            }
            console.warn(`Blocked CORS origin: ${origin}`);
            return callback(new Error(`Not allowed by CORS: ${origin}`));
        },
        methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
        credentials: true,
    });
    app.useStaticAssets((0, path_1.join)(process.cwd(), 'uploads'), {
        prefix: '/uploads/',
    });
    const config = new swagger_1.DocumentBuilder()
        .setTitle('API Documentation')
        .setDescription('API documentation for the service')
        .setVersion('1.0')
        .addBearerAuth()
        .build();
    const document = swagger_1.SwaggerModule.createDocument(app, config);
    if (configService.get('NODE_ENV') !== 'production') {
        swagger_1.SwaggerModule.setup('api-docs', app, document);
    }
    await app.listen(configService.getOrThrow('PORT'));
}
bootstrap();
//# sourceMappingURL=main.js.map