const CryptoJS = require('crypto-js');
const axios = require('axios');

function makeSignatureHeaders(method, url) {
  const timestamp = Date.now();
  const nonce = timestamp + '-' + Math.random().toString(36).substring(2, 15);
  
  let path = url;
  let query = '';
  const queryIndex = url.indexOf('?');
  if (queryIndex !== -1) {
    path = url.substring(0, queryIndex);
    query = url.substring(queryIndex + 1);
  }
  
  const stringToSign = [method, path, query, '', timestamp, nonce].join('\n');
  const signature = CryptoJS.HmacSHA256(stringToSign, 'NovalonManageSystemSecretKey2026');
  const signatureBase64 = CryptoJS.enc.Base64.stringify(signature);
  return {
    'X-Signature': signatureBase64,
    'X-Timestamp': timestamp.toString(),
    'X-Nonce': nonce
  };
}

async function test() {
  try {
    const loginRes = await axios.post('http://localhost:3002/api/auth/login', {
      username: 'admin',
      password: 'Test@123'
    });
    const token = loginRes.data.token;
    console.log('Login OK, token:', token ? token.substring(0, 30) + '...' : 'NONE');

    const sigHeaders = makeSignatureHeaders('POST', '/api/roles');
    const roleRes = await axios.post('http://localhost:3002/api/roles', {
      roleName: 'TestRole_' + Date.now(),
      roleKey: 'test_' + Date.now(),
      roleSort: 99,
      status: 1
    }, {
      headers: {
        'Authorization': 'Bearer ' + token,
        ...sigHeaders
      }
    });
    console.log('Create role status:', roleRes.status);

    await new Promise(r => setTimeout(r, 2000));

    const logSigHeaders = makeSignatureHeaders('GET', '/api/logs/operation/page?page=0&size=10');
    const logRes = await axios.get('http://localhost:3002/api/logs/operation/page?page=0&size=10', {
      headers: {
        'Authorization': 'Bearer ' + token,
        ...logSigHeaders
      }
    });
    console.log('Operation logs total:', logRes.data.totalElements || logRes.data.total || 'unknown');
    const content = logRes.data.content || logRes.data.data || [];
    console.log('Log entries:', content.length);
    if (content.length > 0) {
      console.log('First log:', JSON.stringify(content[0]).substring(0, 300));
    } else {
      console.log('Log response keys:', Object.keys(logRes.data));
      console.log('Log response:', JSON.stringify(logRes.data).substring(0, 500));
    }
  } catch (e) {
    console.error('Error:', e.response ? JSON.stringify(e.response.data) : e.message);
  }
}

test();
