/**
 * Pure-JS database layer using JSON files.
 * No native compilation needed — works on any Node.js environment.
 */
const fs   = require('fs');
const path = require('path');

const DATA_DIR = path.join(__dirname, '..', 'data');
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });

const FILES = {
  runs:   path.join(DATA_DIR, 'runs.json'),
  pages:  path.join(DATA_DIR, 'pages.json'),
  issues: path.join(DATA_DIR, 'issues.json')
};

function read(file) {
  try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return []; }
}
function write(file, data) {
  fs.writeFileSync(file, JSON.stringify(data, null, 2));
}

let _seq = Date.now();
function nextId() { return ++_seq; }

const db = {
  insertRun(id, projectName, url, email) {
    const runs = read(FILES.runs);
    runs.unshift({ id, project_name: projectName, url, email: email||null, status:'running', error:null, pages_found:0, pages_tested:0, total_issues:0, critical_issues:0, warning_issues:0, info_issues:0, created_at: new Date().toISOString(), completed_at:null });
    write(FILES.runs, runs);
  },
  updateRun(id, fields) {
    const runs = read(FILES.runs);
    const idx  = runs.findIndex(r => r.id === id);
    if (idx >= 0) { Object.assign(runs[idx], fields); write(FILES.runs, runs); }
  },
  getRun(id)      { return read(FILES.runs).find(r => r.id === id) || null; },
  getAllRuns()     { return read(FILES.runs).slice(0, 100); },
  deleteRun(id) {
    write(FILES.runs,   read(FILES.runs).filter(r => r.id !== id));
    write(FILES.pages,  read(FILES.pages).filter(p => p.run_id !== id));
    write(FILES.issues, read(FILES.issues).filter(i => i.run_id !== id));
  },
  upsertPage(runId, url, statusCode, loadTime, screenshotDesktop, screenshotMobile) {
    const pages = read(FILES.pages);
    const idx   = pages.findIndex(p => p.run_id === runId && p.url === url);
    const rec   = { id:nextId(), run_id:runId, url, status_code:statusCode, load_time:loadTime, screenshot_desktop:screenshotDesktop, screenshot_mobile:screenshotMobile, created_at:new Date().toISOString() };
    if (idx >= 0) pages[idx] = rec; else pages.push(rec);
    write(FILES.pages, pages);
  },
  getPages(runId) {
    return read(FILES.pages).filter(p => p.run_id === runId).sort((a,b) => a.url.localeCompare(b.url));
  },
  addIssue(runId, pageUrl, severity, type, message, screenshotPath) {
    const issues = read(FILES.issues);
    issues.push({ id:nextId(), run_id:runId, page_url:pageUrl, severity, type, message, screenshot_path:screenshotPath||null, created_at:new Date().toISOString() });
    write(FILES.issues, issues);
  },
  getIssues(runId) {
    const ord = { critical:0, warning:1, info:2 };
    return read(FILES.issues)
      .filter(i => i.run_id === runId)
      .sort((a,b) => (ord[a.severity]??9)-(ord[b.severity]??9) || a.page_url.localeCompare(b.page_url));
  }
};

module.exports = db;
