/**
 * services/advisor-consent.js — consent gate for the read-only advisor panels
 * that access Oracle Diagnostics/Tuning Pack views.
 *
 * These advisors READ pack views (DBA_HIST_*, SQL Access Advisor's DBA_ADVISOR_*)
 * rather than manufacture usage like ADDM Run Now — lower risk, and they already
 * fail closed on ORA-00942. But accessing AWR/pack data is still pack USAGE under
 * Oracle's terms, so they are gated on the same per-connection consent as the rest
 * of the compliance work (db/option-consent.js). Detection informs, consent decides.
 *
 * Two shapes, because the advisors differ:
 *   - advisorConsentDescriptor() → for a route that is ENTIRELY a licensed-view
 *     read (awr-advisor, access-advisor): returns a {licensed:false,
 *     consent_required} object the route merges into its own empty-data response,
 *     so the existing "not licensed" frontend renders unchanged.
 *   - awrConsentAllowed() → for a MIXED route (space-advisor: free usage/frag +
 *     one DBA_HIST growth query): resolve once, run the AWR query only if true.
 *
 * Both fail closed: unset/denied consent or any error → blocked / not allowed.
 */

'use strict';

const { isGranted } = require('../db/option-consent');

function packLabel(optionKey) {
  return optionKey === 'tuning_pack' ? 'Tuning Pack' : 'Diagnostics Pack';
}

/**
 * For a fully licensed-view advisor route. Returns null when the read may proceed
 * (consent granted), or a descriptor to merge into the route's empty-data JSON.
 *
 * @param {number} connectionId
 * @param {string} optionKey   'diagnostics_pack' | 'tuning_pack'
 * @param {string} viewLabel   human phrase, e.g. 'AWR wait-event history'
 */
async function advisorConsentDescriptor(connectionId, optionKey, viewLabel) {
  let granted = false;
  try { granted = await isGranted(connectionId, optionKey); }
  catch (e) { granted = false; } // fail closed
  if (granted) return null;
  return {
    licensed: false,
    consent_required: true,
    option: optionKey,
    not_licensed_reason:
      `Confirm this database is licensed for the Oracle ${packLabel(optionKey)} to load ` +
      `${viewLabel}. TuneVault will not read those views until you confirm — ` +
      `control_management_pack_access defaulting to DIAGNOSTIC+TUNING on Enterprise ` +
      `Edition does not confirm a purchase.`,
  };
}

/**
 * For a mixed route where only some queries touch pack views. True only when the
 * connection has explicit consent for the option; fail-closed on error.
 */
async function awrConsentAllowed(connectionId, optionKey = 'diagnostics_pack') {
  try { return await isGranted(connectionId, optionKey); }
  catch (e) { return false; }
}

module.exports = { advisorConsentDescriptor, awrConsentAllowed };
