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

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

    // Validate required fields
    if (!user_id) {
      return res.status(400).json({ error: 'user_id 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 import_audit_log (
        user_id,
        username,
        product_count,
        request_payload,
        environment,
        target_endpoint,
        use_test_data_source,
        success,
        response_payload,
        error_message,
        created_count,
        errored_count,
        session_id,
        duration_ms
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
      RETURNING id, created_at
    `, [
      user_id,
      username || null,
      product_count || 0,
      JSON.stringify(request_payload),
      environment || 'prod',
      target_endpoint || null,
      use_test_data_source || false,
      success,
      response_payload ? JSON.stringify(response_payload) : null,
      error_message || null,
      created_count || 0,
      errored_count || 0,
      session_id || null,
      duration_ms || null,
    ]);

    res.status(201).json(result.rows[0]);
  } catch (error) {
    console.error('Error creating import audit log:', error);
    res.status(500).json({
      error: 'Failed to create import 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, 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(`user_id = $${paramIndex++}`);
      params.push(user_id);
    }

    if (successFilter !== undefined) {
      conditions.push(`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 import_audit_log ${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
        id,
        user_id,
        username,
        product_count,
        environment,
        target_endpoint,
        use_test_data_source,
        success,
        error_message,
        created_count,
        errored_count,
        session_id,
        duration_ms,
        created_at
      FROM import_audit_log
      ${whereClause}
      ORDER BY 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 import audit log:', error);
    res.status(500).json({
      error: 'Failed to fetch import 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 * FROM import_audit_log WHERE 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 import 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('Import audit log route error:', err);
  res.status(500).json({
    error: 'Internal server error',
    details: err.message
  });
});

export default router;
