<% layout = 'layouts/main' %>
<% title = project ? 'Test Data - ' + project.name : 'Test Data Management' %>

<div class="page-header">
  <h1>Test Data Management</h1>
  <div class="header-actions">
    <% if (typeof projects !== 'undefined' && projects.length > 1) { %>
    <select id="project-select" class="form-input" style="width:auto;" onchange="window.location='/data?project='+this.value">
      <% projects.forEach(p => { %>
      <option value="<%= p.id %>" <%= project && project.id === p.id ? 'selected' : '' %>><%= p.name %></option>
      <% }) %>
    </select>
    <% } %>
    <% if (project) { %>
    <a href="/projects/<%= project.id %>" class="btn">Back</a>
    <% } %>
  </div>
</div>

<div class="alerts" id="alert-container"></div>

<div class="row" style="margin-bottom:2rem;">
  <div class="col col-40">
    <div class="card card-lavender">
      <h3>⚡ Generate Test Data</h3>
      <p style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 1.25rem;">
        Auto-generate realistic synthetic mock datasets for your QA pipeline.
      </p>
      <form id="data-form" class="form">
        <div class="form-group">
          <label>Data Type</label>
          <select id="data-type" class="form-input">
            <option value="users">Users Accounts</option>
            <option value="transactions">Transactions Logs</option>
          </select>
        </div>
        <div class="form-group">
          <label>Record Count</label>
          <input type="number" id="data-count" class="form-input" value="5" min="1" max="100">
        </div>
        <button type="submit" class="btn btn-primary" style="width:100%;margin-top:0.5rem;">Generate Dataset</button>
      </form>
      <div id="data-output" class="output-box" style="display:none;margin-top:1rem;"></div>
    </div>
  </div>
  <div class="col col-60">
    <div class="card">
      <h3>📂 Generated Data Files</h3>
      <% if (dataFiles.length === 0) { %>
      <div class="empty-state" style="padding:2rem 0;">
        <p>No data files generated yet</p>
      </div>
      <% } else { %>
      <table class="info-table">
        <tr><th>File Name</th><th>Size</th><th>Last Modified</th><th>Action</th></tr>
        <% dataFiles.sort((a,b) => new Date(b.modified) - new Date(a.modified)).forEach(f => { %>
        <tr>
          <td><code style="font-family:var(--font-mono);font-size:0.8rem;"><%= f.name %></code></td>
          <td><%= f.size > 1024 ? (f.size / 1024).toFixed(1) + ' KB' : f.size + ' B' %></td>
          <td><%= new Date(f.modified).toLocaleString() %></td>
          <td><button class="btn btn-sm btn-danger" onclick="deleteFile('<%= f.name %>')">Delete</button></td>
        </tr>
        <% }) %>
      </table>
      <% } %>
    </div>
  </div>
</div>

<div class="card">
  <h3>ℹ️ About Test Data Management</h3>
  <p style="color: var(--text-muted); font-size: 0.88rem; line-height:1.5;">
    Generated test data is stored directly in your connected project's <code>data/</code> folder as structured JSON files. These datasets can be easily:
  </p>
  <ul style="color: var(--text-muted); font-size: 0.88rem; padding-left: 1.5rem; margin-top: 0.5rem; line-height:1.6;">
    <li>Read dynamically inside Playwright test scenarios using <code>fs.readFileSync()</code></li>
    <li>Injected directly into a localized sandbox database before test suite runs</li>
    <li>Exported or synced for cross-team quality assurance consistency</li>
  </ul>
</div>

<script>
document.getElementById('data-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  const type = document.getElementById('data-type').value;
  const count = document.getElementById('data-count').value;
  const output = document.getElementById('data-output');

  output.style.display = 'block';
  output.textContent = 'Generating realistic mock data...';
  output.className = 'output-box output-running';

  const res = await fetch('/data/generate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ type, count })
  });
  const data = await res.json();

  if (data.success) {
    output.textContent = `Generated ${data.count} records → ${data.file}`;
    output.className = 'output-box output-success';
    setTimeout(() => location.reload(), 1500);
  } else {
    output.textContent = 'Error: ' + data.error;
    output.className = 'output-box output-error';
  }
});

async function deleteFile(name) {
  if (!confirm(`Are you sure you want to delete ${name}?`)) return;
  const res = await fetch('/data/' + encodeURIComponent(name), { method: 'DELETE' });
  const data = await res.json();
  if (data.success) location.reload();
  else alert('Delete failed');
}
</script>
