import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import fs from 'fs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Use JSON file for data storage (fallback for SQLite compilation issues)
const dbPath = join(__dirname, '../data/adl.json');
// Initialize database file if it doesn't exist
if (!fs.existsSync(join(__dirname, '../data'))) {
fs.mkdirSync(join(__dirname, '../data'), { recursive: true });
}
if (!fs.existsSync(dbPath)) {
fs.writeFileSync(dbPath, JSON.stringify([], null, 2));
}
const readData = () => {
try {
const data = fs.readFileSync(dbPath, 'utf-8');
return JSON.parse(data);
} catch (error) {
return [];
}
};
const writeData = (data) => {
fs.writeFileSync(dbPath, JSON.stringify(data, null, 2));
};
export const getAllEntries = () => {
const entries = readData();
return entries.sort((a, b) => new Date(b.created) - new Date(a.created));
};
export const getEntryById = (id) => {
const entries = readData();
return entries.find(entry => entry.id === id) || null;
};
export const createEntry = (entry) => {
const entries = readData();
entries.push(entry);
writeData(entries);
return entry;
};
export const updateEntry = (id, updates) => {
const entries = readData();
const index = entries.findIndex(entry => entry.id === id);
if (index === -1) return null;
const updated = {
...entries[index],
...updates,
lastEdited: new Date().toISOString()
};
entries[index] = updated;
writeData(entries);
return updated;
};
export const deleteEntry = (id) => {
const entries = readData();
const index = entries.findIndex(entry => entry.id === id);
if (index === -1) return false;
entries.splice(index, 1);
writeData(entries);
return true;
};
export const searchEntries = (searchCriteria) => {
const entries = readData();
return entries.filter(entry => {
// Check author (case-insensitive substring match)
if (searchCriteria.author && !entry.author.toLowerCase().includes(searchCriteria.author.toLowerCase())) {
return false;
}
// Check title (case-insensitive substring match)
if (searchCriteria.title && !entry.title.toLowerCase().includes(searchCriteria.title.toLowerCase())) {
return false;
}
// Check decision (case-insensitive substring match)
if (searchCriteria.decision && !entry.decision.toLowerCase().includes(searchCriteria.decision.toLowerCase())) {
return false;
}
// Check factSheets (case-insensitive substring match in any fact sheet)
if (searchCriteria.factSheets) {
const searchTerm = searchCriteria.factSheets.toLowerCase();
const hasMatch = entry.factSheets.some(fs => fs.toLowerCase().includes(searchTerm));
if (!hasMatch) {
return false;
}
}
// Check status (exact match)
if (searchCriteria.status && entry.status !== searchCriteria.status) {
return false;
}
return true;
}).sort((a, b) => new Date(b.created) - new Date(a.created));
};
export default { getAllEntries, getEntryById, createEntry, updateEntry, deleteEntry, searchEntries };