/**
 * routes/awr-consent.js — passive banner feed for the AWR/Diagnostics-Pack
 * consent prompt.
 *
 * Owns: GET /api/awr-consent/pending — the in-use connections whose
 *       diagnostics_pack consent is still undecided, so the dashboard can show a
 *       non-blocking notice. This is the counterpart to Part 2's blocking modal:
 *       the automatic core-check AWR reads run with no user present (scheduled
 *       runs), so there is nothing to block — instead we surface a passive prompt
 *       the next time a human looks.
 * Does NOT own: the gate itself (lib/awr-consent.js + oracle-client.js), or
 *       recording consent (routes/option-consent.js POST).
 *
 * "In use" = at least one completed, non-demo health check exists, so brand-new
 * connections don't nag before they've run. Only 'unset' surfaces — a customer
 * who explicitly denied is not prompted again.
 */

'use strict';

const express = require('express');
const pool = require('../db/index');
const { requireAuth } = require('../middleware/auth');

const router = express.Router();

// GET /api/awr-consent/pending
router.get('/pending', requireAuth, async (req, res) => {
  try {
    const { rows } = await pool.query(
      `SELECT oc.id, oc.name, oc.service_name
         FROM oracle_connections oc
        WHERE oc.user_id = $1
          AND EXISTS (
            SELECT 1 FROM health_checks hc
             WHERE hc.connection_id = oc.id
               AND hc.status = 'completed'
               AND hc.is_demo = false
          )
          AND NOT EXISTS (
            SELECT 1 FROM connection_option_consent c
             WHERE c.connection_id = oc.id
               AND c.option_key = 'diagnostics_pack'
               AND c.state IN ('granted', 'denied')
          )
        ORDER BY oc.name NULLS LAST, oc.id`,
      [req.user.id]
    );
    res.json({ pending: rows, count: rows.length });
  } catch (err) {
    console.error('[awr-consent/pending] error:', err.message);
    res.status(500).json({ error: 'Failed to load AWR consent status' });
  }
});

module.exports = router;
