#!/bin/bash
echo "Creating backend files..."

# Database config
cat > config/database.js << 'EOF'
const { Pool } = require('pg');
require('dotenv').config();

const pool = new Pool({
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 5432,
  database: process.env.DB_NAME || 'skyartshop',
  user: process.env.DB_USER || 'skyartapp',
  password: process.env.DB_PASSWORD,
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});

pool.on('connect', () => console.log('✓ PostgreSQL connected'));
pool.on('error', (err) => console.error('PostgreSQL error:', err));

const query = async (text, params) => {
  const start = Date.now();
  try {
    const res = await pool.query(text, params);
    const duration = Date.now() - start;
    console.log('Executed query', { text, duration, rows: res.rowCount });
    return res;
  } catch (error) {
    console.error('Query error:', error);
    throw error;
  }
};

module.exports = { pool, query };
EOF

# Auth middleware
cat > middleware/auth.js << 'EOF'
const requireAuth = (req, res, next) => {
  if (req.session && req.session.adminId) {
    return next();
  }
  res.redirect('/admin/login');
};

const requireRole = (allowedRoles) => {
  return (req, res, next) => {
    if (!req.session || !req.session.adminId) {
      return res.redirect('/admin/login');
    }
    const userRole = req.session.role || 'user';
    if (allowedRoles.includes(userRole)) {
      return next();
    }
    res.status(403).send('Access denied');
  };
};

const redirectIfAuth = (req, res, next) => {
  if (req.session && req.session.adminId) {
    return res.redirect('/admin/dashboard');
  }
  next();
};

module.exports = { requireAuth, requireRole, redirectIfAuth };
EOF

echo "✓ Files created successfully"
