import { loadConfig } from './config.js';
import { closeDb } from './db/connection.js';
import { buildApp } from './app.js';
import { findFreePort } from './utils/find-free-port.js';
import fs from 'node:fs';
import path from 'node:path';
const config = loadConfig();
const app = await buildApp();
// Graceful shutdown
const shutdown = async (signal) => {
    app.log.info(`Received ${signal}, shutting down...`);
    await app.close();
    closeDb();
    // Clean up port file
    const portFile = path.resolve(process.cwd(), '.server-port');
    try {
        fs.unlinkSync(portFile);
    }
    catch { /* ignore */ }
    process.exit(0);
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
// Find a free port starting from the configured one
const port = await findFreePort(config.port);
// Write port to file so frontend dev server can discover it
const portFile = path.resolve(process.cwd(), '.server-port');
const serverUrl = `http://127.0.0.1:${port}`;
fs.writeFileSync(portFile, `${port}`, 'utf-8');
console.log(`[port] ${port} (${portFile})`);
if (port !== config.port) {
    app.log.warn(`Port ${config.port} is busy — using port ${port} instead`);
}
await app.listen({ port, host: '0.0.0.0' });
app.log.info(`Server listening on port ${port}`);
//# sourceMappingURL=index.js.map