import express from 'express';
const router = express.Router();

// Create a new audit log entry
router.post('/', async (req, res) => {
  try {
    const {
      user_id,
      username,
      pid,
      action,
      request_payload,
      target_endpoint,
      success,
      response_payload,
      error_message,
      duration_ms,
    } = req.body;

    // Validate required fields
    if (!user_id) {
      return res.status(400).json({ error: 'user_id is required' });
    }
    if (!pid) {
      return res.status(400).json({ error: 'pid is required' });
    }
    if (!action) {
      return res.status(400).json({ error: 'action is required' });
    }
    if (!request_payload) {
      return res.status(400).json({ error: 'request_payload is required' });
    }
    if (typeof success !== 'boolean') {
      return res.status(400).json({ error: 'success (boolean) is required' });
    }

    const pool = req.app.locals.pool;
    if (!pool) {
      throw new Error('Database pool not initialized');
    }

    const result = await pool.query(`
      INSERT INTO product_editor_audit_log (
        user_id,
        username,
        pid,
        action,
        request_payload,
        target_endpoint,
        success,
        response_payload,
        error_message,
        duration_ms
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
      RETURNING id, created_at
    `, [
      user_id,
      username || null,
      pid,
      action,
      JSON.stringify(request_payload),
      target_endpoint || null,
      success,
      response_payload ? JSON.stringify(response_payload) : null,
      error_message || null,
      duration_ms || null,
    ]);

    res.status(201).json(result.rows[0]);
  } catch (error) {
    console.error('Error creating product editor audit log:', error);
    res.status(500).json({
      error: 'Failed to create product editor audit log',
      details: error instanceof Error ? error.message : 'Unknown error'
    });
  }
});

// List audit log entries (with pagination)
router.get('/', async (req, res) => {
  try {
    const { user_id, pid, action, limit = 50, offset = 0, success: successFilter } = req.query;

    const pool = req.app.locals.pool;
    if (!pool) {
      throw new Error('Database pool not initialized');
    }

    const conditions = [];
    const params = [];
    let paramIndex = 1;

    if (user_id) {
      conditions.push(`a.user_id = $${paramIndex++}`);
      params.push(user_id);
    }

    if (pid) {
      conditions.push(`a.pid = $${paramIndex++}`);
      params.push(pid);
    }

    if (action) {
      conditions.push(`a.action = $${paramIndex++}`);
      params.push(action);
    }

    if (successFilter !== undefined) {
      conditions.push(`a.success = $${paramIndex++}`);
      params.push(successFilter === 'true');
    }

    const whereClause = conditions.length > 0
      ? `WHERE ${conditions.join(' AND ')}`
      : '';

    // Get total count
    const countResult = await pool.query(
      `SELECT COUNT(*) FROM product_editor_audit_log a ${whereClause}`,
      params
    );

    // Get paginated results (exclude large payload columns in list view)
    const dataParams = [...params, parseInt(limit, 10), parseInt(offset, 10)];
    const result = await pool.query(`
      SELECT
        a.id,
        a.user_id,
        a.username,
        a.pid,
        p.title AS product_name,
        a.action,
        a.target_endpoint,
        a.success,
        a.error_message,
        a.duration_ms,
        a.created_at
      FROM product_editor_audit_log a
      LEFT JOIN products p ON p.pid = a.pid
      ${whereClause}
      ORDER BY a.created_at DESC
      LIMIT $${paramIndex++} OFFSET $${paramIndex++}
    `, dataParams);

    res.json({
      total: parseInt(countResult.rows[0].count, 10),
      entries: result.rows,
    });
  } catch (error) {
    console.error('Error fetching product editor audit log:', error);
    res.status(500).json({
      error: 'Failed to fetch product editor audit log',
      details: error instanceof Error ? error.message : 'Unknown error'
    });
  }
});

// Get a single audit log entry (with full payloads)
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const pool = req.app.locals.pool;
    if (!pool) {
      throw new Error('Database pool not initialized');
    }

    const result = await pool.query(
      'SELECT a.*, p.title AS product_name FROM product_editor_audit_log a LEFT JOIN products p ON p.pid = a.pid WHERE a.id = $1',
      [id]
    );

    if (result.rows.length === 0) {
      return res.status(404).json({ error: 'Audit log entry not found' });
    }

    res.json(result.rows[0]);
  } catch (error) {
    console.error('Error fetching product editor audit log entry:', error);
    res.status(500).json({
      error: 'Failed to fetch audit log entry',
      details: error instanceof Error ? error.message : 'Unknown error'
    });
  }
});

// Error handling middleware
router.use((err, req, res, next) => {
  console.error('Product editor audit log route error:', err);
  res.status(500).json({
    error: 'Internal server error',
    details: err.message
  });
});

export default router;
