"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 });
exports.prisma = void 0;
const express_1 = __importDefault(require("express"));
const cors_1 = __importDefault(require("cors"));
const client_1 = require("@prisma/client");
const auth_1 = __importDefault(require("./routes/auth"));
const articles_1 = __importDefault(require("./routes/articles"));
const promos_1 = __importDefault(require("./routes/promos"));
const promo_categories_1 = __importDefault(require("./routes/promo-categories"));
const bookings_1 = __importDefault(require("./routes/bookings"));
const locations_1 = __importDefault(require("./routes/locations"));
const testimonials_1 = __importDefault(require("./routes/testimonials"));
const banners_1 = __importDefault(require("./routes/banners"));
const treatments_1 = __importStar(require("./routes/treatments"));
const categories_1 = __importDefault(require("./routes/categories"));
const doctors_1 = __importDefault(require("./routes/doctors"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const prisma = new client_1.PrismaClient();
exports.prisma = prisma;
const app = (0, express_1.default)();
const PORT = process.env.PORT || 5000;
// Ensure uploads directory exists - use absolute path from project root
// __dirname is backend/src, go up 2 levels to backend, then up 1 to carla-skin-clinic-web root
const projectRoot = path_1.default.join(__dirname, '..', '..');
const uploadsDir = path_1.default.join(projectRoot, 'uploads');
const promosDir = path_1.default.join(projectRoot, 'public', 'images', 'promo');
if (!fs_1.default.existsSync(uploadsDir))
    fs_1.default.mkdirSync(uploadsDir, { recursive: true });
if (!fs_1.default.existsSync(promosDir))
    fs_1.default.mkdirSync(promosDir, { recursive: true });
// Middleware
app.use((0, cors_1.default)({
    origin: [
        'http://localhost:3000',
        'http://localhost:3001',
        'http://localhost:3002',
        'http://localhost:3003',
        'http://localhost:3004',
        'http://localhost:5173',
        process.env.FRONTEND_URL || 'http://localhost:3000'
    ],
    credentials: true
}));
app.use(express_1.default.json());
app.use(express_1.default.urlencoded({ extended: true }));
// Serve uploaded promo images from public/images/promo (accessible via /images/promo) - MUST BE BEFORE /images
app.use('/images/promo', express_1.default.static(promosDir));
// Serve static files from public/images folder
app.use('/images', express_1.default.static(path_1.default.join(projectRoot, 'public')));
// Serve uploaded files (article images, etc.) from uploads/ folder
app.use('/uploads', express_1.default.static(uploadsDir));
// Routes
app.use('/api/auth', auth_1.default);
app.use('/api/articles', articles_1.default);
app.use('/api/promos', promos_1.default);
app.use('/api/promo-categories', promo_categories_1.default);
app.use('/api/bookings', bookings_1.default);
app.use('/api/locations', locations_1.default);
app.use('/api/testimonials', testimonials_1.default);
app.use('/api/banners', banners_1.default);
app.use('/api/treatments', treatments_1.default);
app.use('/api/treatment-categories', treatments_1.categoryRouter);
app.use('/api/doctors', doctors_1.default);
app.use('/api/categories', categories_1.default);
// Health check
app.get('/api/health', (req, res) => {
    res.json({
        status: 'ok',
        timestamp: new Date().toISOString(),
        environment: process.env.NODE_ENV || 'development',
        database: 'connected'
    });
});
// 404 handler
app.use((req, res) => {
    res.status(404).json({ message: 'Endpoint tidak ditemukan' });
});
// Error handler
app.use((err, req, res, next) => {
    console.error('❌ Error:', err.stack);
    res.status(err.status || 500).json({
        message: err.message || 'Terjadi kesalahan server',
        error: process.env.NODE_ENV === 'development' ? err.message : undefined
    });
});
// Retry database connection on startup
async function startServer() {
    let retries = 10;
    while (retries > 0) {
        try {
            await prisma.$connect();
            console.log('✅ Database connected');
            break;
        }
        catch (err) {
            retries -= 1;
            console.log(`⏳ Waiting for database... (${retries} retries left)`);
            await new Promise(res => setTimeout(res, 3000));
        }
    }
    if (retries === 0) {
        console.error('❌ Could not connect to database after 10 retries');
        process.exit(1);
    }
    app.listen(PORT, () => {
        console.log(`🚀 Server running on port ${PORT}`);
        console.log(`📡 Environment: ${process.env.NODE_ENV || 'development'}`);
        console.log(`🌐 CORS enabled for: ${process.env.FRONTEND_URL || 'http://localhost:3000'}`);
    });
}
startServer().catch(err => {
    console.error('Failed to start server:', err);
    process.exit(1);
});
// Graceful shutdown
process.on('SIGTERM', async () => {
    console.log('SIGTERM received, shutting down gracefully...');
    await prisma.$disconnect();
    process.exit(0);
});
//# sourceMappingURL=index.js.map