const express = require('express');
const cors = require('cors');
const { Pool } = require('pg');
const { createClient } = require('redis');
const cookieParser = require('cookie-parser');
require('dotenv').config();

const app = express();
const port = process.env.PORT || 4001;

app.use(cors({ origin: 'http://localhost:4000', credentials: true }));
app.use(express.json());

// Routes
const authRoutes = require('./routes/auth');
const qrRoutes = require('./routes/qr');
const redirectRoutes = require('./routes/redirect');
const analyticsRoutes = require('./routes/analytics');
const adminRoutes = require('./routes/admin');
const paymentsRoutes = require('./routes/payments');

app.use('/api/auth', authRoutes);
app.use('/api/qr', qrRoutes);
app.use('/api/analytics', analyticsRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/payments', paymentsRoutes);
app.use('/l', redirectRoutes);

// Postgres setup
const pgPool = new Pool({
  host: process.env.PGHOST || 'postgres',
  port: process.env.PGPORT || 5432,
  user: process.env.PGUSER || 'postgres',
  password: process.env.PGPASSWORD || 'postgres',
  database: process.env.PGDATABASE || 'ckqr',
});

// Redis setup
const redisClient = createClient({
  url: `redis://${process.env.REDIS_HOST || 'redis'}:${process.env.REDIS_PORT || 6379}`
});

redisClient.on('error', (err) => console.log('Redis Client Error', err));

app.get('/api/health', async (req, res) => {
  let pgStatus = 'Unknown';
  let redisStatus = 'Unknown';

  try {
    const pgRes = await pgPool.query('SELECT NOW()');
    pgStatus = 'Connected';
  } catch (err) {
    pgStatus = `Error: ${err.message}`;
  }

  try {
    if (!redisClient.isOpen) {
      await redisClient.connect();
    }
    await redisClient.ping();
    redisStatus = 'Connected';
  } catch (err) {
    redisStatus = `Error: ${err.message}`;
  }

  res.json({
    status: 'ok',
    services: {
      api: 'Running',
      postgres: pgStatus,
      redis: redisStatus
    }
  });
});

app.listen(port, () => {
  console.log(`CK-QR API listening on port ${port}`);
});
