// ── Shard feature visibility (model) ───────────────────────────────────────
//
// Thin row-shaping layer over shardVisibility.db. The policy — the ladder, the
// feature catalog, the locked fields, the kind→feature map — lives in
// utils/shardVisibility.js; this file only reads and writes rows.

const db = require('./shardVisibility.db')

// The `field_rules` JSON column comes back as a string on the mariadb driver.
function parseRules(raw) {
  if (raw == null) return {}
  if (typeof raw === 'object') return raw
  try {
    const parsed = JSON.parse(raw)
    return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
  } catch {
    return {}
  }
}

const toSafe = (row) =>
  row && {
    feature: row.feature,
    enabled: !!row.enabled,
    audience: row.audience,
    stream: row.stream == null ? null : !!row.stream,
    fieldRules: parseRules(row.field_rules),
    updatedBy: row.updated_by,
    updatedAt: row.updated_at,
  }

async function listAll() {
  const rows = await db.listAll()
  return rows.map(toSafe)
}

async function getOne(feature) {
  const rows = await db.getOne(feature)
  return toSafe(rows[0])
}

const upsert = (entry) => db.upsert(entry)

module.exports = { listAll, getOne, upsert }
