const database = require('../config/database');

class FeatureBusinessRules {
  static async upsert(template_id, feature_id, rules) {
    // Normalize to JSON array
    let businessRules;
    if (Array.isArray(rules)) {
      businessRules = rules.map((r) => (typeof r === 'string' ? tryParse(r) ?? r : r));
    } else if (typeof rules === 'string') {
      const parsed = tryParse(rules);
      businessRules = Array.isArray(parsed) ? parsed : [parsed ?? rules];
    } else if (rules && typeof rules === 'object') {
      businessRules = [rules];
    } else {
      businessRules = [];
    }

    const sql = `
      INSERT INTO feature_business_rules (template_id, feature_id, business_rules, updated_at)
      VALUES ($1, $2, $3::jsonb, NOW())
      ON CONFLICT (template_id, feature_id)
      DO UPDATE SET business_rules = EXCLUDED.business_rules, updated_at = NOW()
      RETURNING *
    `;
    const result = await database.query(sql, [template_id, feature_id, JSON.stringify(businessRules)]);
    return result.rows[0];
  }
}

function tryParse(s) {
  try {
    const t = String(s).trim();
    if ((t.startsWith('{') && t.endsWith('}')) || (t.startsWith('[') && t.endsWith(']'))) {
      return JSON.parse(t);
    }
    return null;
  } catch {
    return null;
  }
}

module.exports = FeatureBusinessRules;


