const express = require('express'); const { Pool } = require('pg'); const path = require('path'); const app = express(); const PORT = process.env.PORT || 3000; // PostgreSQL connection const pool = new Pool({ connectionString: process.env.DATABASE_URL, ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false, }); // Initialize DB table async function initDB() { const client = await pool.connect(); try { await client.query(` CREATE TABLE IF NOT EXISTS todos ( id SERIAL PRIMARY KEY, text TEXT NOT NULL, done BOOLEAN DEFAULT FALSE, created_at TIMESTAMP DEFAULT NOW() ) `); console.log('⚡ DATABASE ONLINE ⚡'); } finally { client.release(); } } app.use(express.urlencoded({ extended: true })); app.use(express.static(path.join(__dirname, 'public'))); app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // Routes app.get('/', async (req, res) => { try { const result = await pool.query('SELECT * FROM todos ORDER BY created_at DESC'); res.render('index', { todos: result.rows, error: null }); } catch (err) { res.render('index', { todos: [], error: 'DATABASE CONNECTION LOST ⚠' }); } }); app.post('/add', async (req, res) => { const { text } = req.body; if (text && text.trim()) { await pool.query('INSERT INTO todos (text) VALUES ($1)', [text.trim()]); } res.redirect('/'); }); app.post('/toggle/:id', async (req, res) => { await pool.query('UPDATE todos SET done = NOT done WHERE id = $1', [req.params.id]); res.redirect('/'); }); app.post('/delete/:id', async (req, res) => { await pool.query('DELETE FROM todos WHERE id = $1', [req.params.id]); res.redirect('/'); }); // Health check app.get('/health', (req, res) => res.json({ status: 'ONLINE', db: 'CONNECTED' })); initDB().then(() => { app.listen(PORT, () => { console.log(`╔══════════════════════════════════════╗`); console.log(`║ ⚡ TECHNO-TODO v1.0 ONLINE ⚡ ║`); console.log(`║ PORT: ${PORT} ║`); console.log(`╚══════════════════════════════════════╝`); }); }).catch(err => { console.error('Failed to init DB:', err); process.exit(1); });