const { Pool } = require('pg'); // Database connection configuration const mainDbConfig = { connectionString: 'postgresql://cd_owner:npg_HvkFi0YfQT9u@ep-muddy-river-a1za2spe-pooler.ap-southeast-1.aws.neon.tech/cd?sslmode=require' }; // Create database pool const mainPool = new Pool(mainDbConfig); async function initializeDatabase() { try { // Drop tables in correct order to handle foreign key constraints await mainPool.query('DROP TABLE IF EXISTS messages CASCADE'); await mainPool.query('DROP TABLE IF EXISTS submissions CASCADE'); await mainPool.query('DROP TABLE IF EXISTS users CASCADE'); await mainPool.query('DROP TABLE IF EXISTS otps CASCADE'); // Create users table await mainPool.query(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ) `); // Create OTP table await mainPool.query(` CREATE TABLE IF NOT EXISTS otps ( id SERIAL PRIMARY KEY, email VARCHAR(255) NOT NULL, otp VARCHAR(6) NOT NULL, is_used BOOLEAN DEFAULT FALSE, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, expires_at TIMESTAMP WITH TIME ZONE NOT NULL ) `); // Create submissions table await mainPool.query(` CREATE TABLE IF NOT EXISTS submissions ( id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id), ticket_user_name VARCHAR(255) NOT NULL, ticket_number VARCHAR(255) NOT NULL, gc_name VARCHAR(255) NOT NULL, gc_code VARCHAR(255) NOT NULL, upi_id VARCHAR(255) NOT NULL, amount DECIMAL(10,2) NOT NULL, proof_video_url TEXT NOT NULL, status VARCHAR(50) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected', 'paid', 'closed')), created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ) `); // Create messages table await mainPool.query(` CREATE TABLE IF NOT EXISTS messages ( id SERIAL PRIMARY KEY, submission_id INTEGER REFERENCES submissions(id), sender_type VARCHAR(50) CHECK (sender_type IN ('user', 'admin')), message TEXT NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ) `); console.log('Database tables initialized successfully'); } catch (error) { console.error('Error initializing database:', error); throw error; } } // Test database connection mainPool.query('SELECT NOW()', (err, res) => { if (err) { console.error('Error connecting to database:', err); } else { console.log('Connected to main database'); initializeDatabase(); } }); module.exports = { mainPool, initializeDatabase }; // If this file is run directly, initialize the database if (require.main === module) { initializeDatabase(); }