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

const dbPath = path.resolve(__dirname, 'prod.db');
const dirPath = __dirname;

console.log('--- GymFlow Database Permission Check ---');
console.log(`Checking directory: ${dirPath}`);
console.log(`Checking file: ${dbPath}`);

// 1. Check Directory
try {
    fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
    console.log('✅ Directory is readable and writable.');
} catch (err) {
    console.error('❌ Directory is NOT writable! SQLite needs directory write access to create temporary files.');
}

// 2. Check File
if (fs.existsSync(dbPath)) {
    try {
        fs.accessSync(dbPath, fs.constants.R_OK | fs.constants.W_OK);
        console.log('✅ Database file is readable and writable.');
    } catch (err) {
        console.error('❌ Database file is NOT writable!');
    }
} else {
    console.log('ℹ️ Database file does not exist yet.');
}

// 3. Try to write a test file in the directory
const testFile = path.join(dirPath, '.write_test');
try {
    fs.writeFileSync(testFile, 'test');
    fs.unlinkSync(testFile);
    console.log('✅ Successfully performed a test write in the directory.');
} catch (err) {
    console.error(`❌ Failed test write in directory: ${err.message}`);
}

console.log('\n--- Recommendation ---');
console.log('If any checks failed, run these commands on your NAS (in the gymflow/server folder):');
console.log('1. sudo chmod 777 .');
console.log('2. sudo chmod 666 prod.db');
console.log('\nAlternatively, ensure your Docker container is running with a user that owns these files.');
