const { query } = require('../../utils/db')

// One row per shard feature. Absent rows are fine — utils/shardVisibility.js
// compiles a default for every known feature and merges stored rows over it, so
// a fresh install with an empty table behaves exactly as the site did pre-v3.

const COLS = 'feature, enabled, audience, stream, field_rules, updated_by, updated_at'

const listAll = () => query(`SELECT ${COLS} FROM shard_feature_visibility`)

const getOne = (feature) =>
  query(`SELECT ${COLS} FROM shard_feature_visibility WHERE feature = ?`, [feature])

// Upsert one feature's settings. `fieldRules` is stored as a JSON object of
// {field: rung}; the caller has already stripped locked fields and validated
// every rung against the ladder.
const upsert = ({ feature, enabled, audience, stream, fieldRules, updatedBy }) =>
  query(
    `INSERT INTO shard_feature_visibility (feature, enabled, audience, stream, field_rules, updated_by)
     VALUES (?, ?, ?, ?, ?, ?)
     ON DUPLICATE KEY UPDATE
       enabled     = VALUES(enabled),
       audience    = VALUES(audience),
       stream      = VALUES(stream),
       field_rules = VALUES(field_rules),
       updated_by  = VALUES(updated_by)`,
    [
      feature,
      enabled ? 1 : 0,
      audience,
      stream ? 1 : 0,
      fieldRules == null ? null : JSON.stringify(fieldRules),
      updatedBy ?? null,
    ],
  )

module.exports = { listAll, getOne, upsert }
