const express = require('express');
const router = express.Router();
const db = require('../db');

// ============================
// Update KYC Status API
// ============================
// URL: POST /ovira/api/kyc/update-status
// BODY: { user_id: 5, status: 'approved' }
// ============================
router.post('/', (req, res) => {
  const { kyc_id, status } = req.body;

  if (!kyc_id || !status) {
    return res.status(400).json({ message: 'user_id and status are required' });
  }

  // Ensure only allowed statuses
  const allowedStatuses = ['pending', 'approved', 'rejected'];
  if (!allowedStatuses.includes(status.toLowerCase())) {
    return res.status(400).json({ message: 'Invalid status value' });
  }

  const query = 'UPDATE kyc_details SET status=? WHERE id=?';
  db.query(query, [status, kyc_id], (err, result) => {
    if (err) {
      console.error('DB Error:', err);
      return res.status(500).json({ message: 'Database error', error: err });
    }

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: 'KYC record not found for this user' });
    }

    res.json({ message: 'KYC status updated successfully', kyc_id, status });
  });
});

module.exports = router;
