// Glue layer: normalize data shapes + role/alias exports for admin modules.
// Runs AFTER data.jsx.

(function(){
  // Rename/alias for modules
  window.AUDIT_LOG = (window.AUDIT || []).map(a => ({
    id: a.id,
    timestamp: (a.created_at || '').replace('T', ' ').slice(0, 16),
    actor: a.user,
    action: a.action,
    target: a.table_name,
    details: Object.entries(a.details || {}).map(([k,v]) => `${k}: ${v}`).join(', '),
    ip: '41.202.' + (10 + (a.id?.charCodeAt(1)||0) % 200) + '.' + (50 + (a.id?.charCodeAt(0)||0) % 200),
  }));

  // Normalize DEPOSITS (data uses amount_fcfa / bank_name / receipt_number)
  window.DEPOSITS = (window.DEPOSITS || []).map(d => ({
    id: d.id,
    deposit_date: d.deposit_date,
    source: d.description || d.source || '—',
    method: d.method || (d.bank_name?.includes('BCA') ? 'transfer' : 'cash'),
    amount: d.amount_fcfa ?? d.amount ?? 0,
    recorded_by: d.recorded_by,
    status: d.status || 'confirmed',
    reference: d.receipt_number || d.reference || '—',
  }));

  // USER_ACCOUNTS: combine active employees + waitlist into one user directory
  const emps = (window.EMPLOYEES || []).map(e => ({
    id: 'acc_' + e.id,
    full_name: e.full_name,
    email: e.email,
    role: e.role,
    status: e.status === 'active' ? 'active' : e.status === 'waitlist' ? 'pending_approval' : e.status,
    last_login: e.status === 'active' ? '2026-04-20 07:' + String(10 + (e.id?.charCodeAt(1)||0) % 50).padStart(2,'0') : null,
    created_at: e.join_date,
    requested_role: e.role,
    requested_at: e.join_date,
  }));
  const wait = (window.WAITLIST_USERS || []).map(w => ({
    id: 'acc_' + w.id,
    full_name: w.full_name,
    email: w.email,
    role: w.role,
    status: 'pending_approval',
    last_login: null,
    created_at: w.requested_at,
    requested_role: w.role,
    requested_at: w.requested_at,
  }));
  window.USER_ACCOUNTS = [...emps.slice(0, 10), ...wait, ...(Math.random() > 2 ? [] : [])];

  // Production batches — add display fields the module expects (runs after admin-store merge)
  window.BATCHES = (window.BATCHES || []).map(b => ({
    id: b.id,
    flavor: b.flavor || b.flavor_name,
    quantity_kg: b.quantity_kg ?? b.qty ?? 15,
    batch_date: b.batch_date || b.date || '2026-04-18',
    produced_by: b.produced_by || b.operator || 'Fatimé Ousmane',
    status: b.status || 'completed',
    notes: b.notes || '',
  }));
})();
