const fs = require('fs');
const path = require('path');

class JSONDatabase {
    constructor(filePath) {
        this.filePath = filePath;
        this.readFile = this.readFile.bind(this); // Bind readFile method to the instance
        this.writeFile = this.writeFile.bind(this); // Bind writeFile method to the instance

    }

    readFile() {
        if (!fs.existsSync(this.filePath)) {
            console.log('File does not exist, returning null:', this.filePath);
            return null;
        }
        try {
            const data = fs.readFileSync(this.filePath, 'utf8');
            return JSON.parse(data);
        } catch (error) {
            console.error('Error reading file:', error);
            return null;
        }
    }

    writeFile(data) {
        try {
            fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2), { flag: 'w' });
            console.log('File written successfully.');
        } catch (error) {
            console.error('Error writing file:', error);
        }
    }

    isKeyValue(key, value) {
        const data = this.readFile();
        if (!data) {
            return false;
        }

        for (const item of data) {
            if (item[key] === value) {
                return true;
            }
        }
        return false;
    }

    findIndexByKeyValueInArray(key, value) {
        const data = this.readFile();
        if (!data || !Array.isArray(data)) {
            return -1;
        }

        for (let i = 0; i < data.length; i++) {
            if (data[i][key] === value) {
                return i;
            }
        }
        return -1;
    }

    findByKeyValue(key, value) {
        const data = this.readFile();
        if (!data || !Array.isArray(data)) {
            return null; // Database read failed or data is not an array
        }

        for (const item of data) {
            if (item[key] === value) {
                return item; // Return the object containing the specified key-value pair
            }
        }
        return null; // No matching key-value pair found
    }
}

const usersDB = new JSONDatabase(path.join(__dirname, 'users.json'));
const departmentsDB = new JSONDatabase(path.join(__dirname, 'departments.json'));
const backupSchemesDB = new JSONDatabase(path.join(__dirname, 'backup_schemes.json'));
const ceoDB = new JSONDatabase(path.join(__dirname, 'ceo.json'));
const adminDB = new JSONDatabase(path.join(__dirname + '..', '..', '..', '..', 'frontend', 'config', 'credentials.json'));

module.exports = {
    usersDB,
    departmentsDB,
    backupSchemesDB,
    ceoDB,
    adminDB,
    JSONDatabase
};
