require('dotenv').config({ path: '../.env' });
const express = require('express');
const cors = require('cors');
const { Pool } = require('pg');
const morgan = require('morgan');
const chatRoutes = require('./routes');

// Log startup configuration
console.log('Starting chat server with config:', {
  host: process.env.CHAT_DB_HOST,
  user: process.env.CHAT_DB_USER,
  database: process.env.CHAT_DB_NAME || 'rocketchat_converted',
  port: process.env.CHAT_DB_PORT,
  chat_port: process.env.CHAT_PORT || 3014
});

const app = express();
const port = process.env.CHAT_PORT || 3014;

// Database configuration for rocketchat_converted database
const pool = new Pool({
  host: process.env.CHAT_DB_HOST,
  user: process.env.CHAT_DB_USER,
  password: process.env.CHAT_DB_PASSWORD,
  database: process.env.CHAT_DB_NAME || 'rocketchat_converted',
  port: process.env.CHAT_DB_PORT,
});

// Make pool available globally
global.pool = pool;

// Middleware
app.use(express.json());
app.use(morgan('combined'));
app.use(cors({
  origin: ['http://localhost:5175', 'http://localhost:5174', 'https://inventory.kent.pw'],
  credentials: true
}));

// Test database connection endpoint
app.get('/test-db', async (req, res) => {
  try {
    const result = await pool.query('SELECT COUNT(*) as user_count FROM users WHERE active = true');
    const messageResult = await pool.query('SELECT COUNT(*) as message_count FROM message');
    const roomResult = await pool.query('SELECT COUNT(*) as room_count FROM room');
    
    res.json({
      status: 'success',
      database: 'rocketchat_converted',
      stats: {
        active_users: parseInt(result.rows[0].user_count),
        total_messages: parseInt(messageResult.rows[0].message_count),
        total_rooms: parseInt(roomResult.rows[0].room_count)
      }
    });
  } catch (error) {
    console.error('Database test error:', error);
    res.status(500).json({ 
      status: 'error',
      error: 'Database connection failed',
      details: error.message
    });
  }
});

// Mount all routes from routes.js
app.use('/', chatRoutes);

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'healthy' });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something broke!' });
});

// Start server
app.listen(port, () => {
  console.log(`Chat server running on port ${port}`);
}); 