const express = require('express');
const sql = require('mssql');
const cors = require('cors');
const path = require('path'); 

const app = express();
app.use(cors());

const sqlconfig = {
    server: '192.168.13.30',
    database: 'NewDatabase',
    user: 'sa',
    password: 'sa@12345',
    options: {
        encrypt: false,
        trustServerCertificate: true,
        trustedConnection: true,
    },
};

// Root route
app.get('/', (req, res) => {
    res.send('Welcome to the PDF Search API!');
});

// Search route
app.get('/search', async (req, res) => {
    const { keyword } = req.query;

    if (!keyword) {
        return res.status(400).send('No search keyword provided');
    }

    try {
        await sql.connect(sqlconfig);

        // Split the keyword into individual words (support for multi-word searches)
        const words = keyword.split(/\s+/).map(word => word.trim()).filter(Boolean);

        if (words.length === 0) {
            return res.status(400).send('Invalid keyword');
        }

        // Sanitize input by removing special characters (optional but good practice)
        const sanitizedWords = words.map(word => word.replace(/[^\w\s]/g, '')); // Remove non-alphanumeric characters

        if (sanitizedWords.length === 0) {
            return res.status(400).send('Invalid keyword');
        }

        // Log to check the sanitized words
        console.log('Sanitized words:', sanitizedWords);

        // Build dynamic query with LIKE for each word (AND logic to ensure all words are matched)
        let query = 'SELECT Filename FROM files WHERE ';
        const request = new sql.Request();

        sanitizedWords.forEach((word, index) => {
            const paramName = `word${index}`;
            query += `PdfData LIKE @${paramName} `;
            if (index < sanitizedWords.length - 1) query += 'AND ';  // Use AND instead of OR to require all words
            request.input(paramName, sql.NVarChar, `%${word}%`);
        });

        // Log the final query to check the format
        console.log('Generated SQL Query:', query);

        // Execute the query
        const result = await request.query(query);
        res.send(result.recordset);

    } catch (err) {
        console.error('SQL error:', err);
        res.status(500).send('Error searching PDFs');
    } finally {
        await sql.close();
    }
});


// Serve PDF files
app.get('/files/*', (req, res) => {
    let relativePath = req.params[0]; // Everything after /files/
    relativePath = relativePath.replace(/\//g, '\\'); // Convert forward slashes to backslashes

    const baseDir = '\\\\192.168.13.30\\c$\\GGN Office Repository'; 
    const filePath = path.join(baseDir, relativePath);

    // Security check: Ensure the filePath starts with baseDir to prevent path traversal
    if (!filePath.startsWith(baseDir)) {
        return res.status(400).send('Invalid file path');
    }

    res.sendFile(filePath, (err) => {
        if (err) {
            console.error('File send error:', err);
            res.status(err.status || 500).send('Error accessing file');
        }
    });
});

// CORS settings (Move this before routes for better practice)
app.use(cors({
    origin: 'http://192.168.7.175:3000', 
    methods: 'GET,POST',
}));

// Error handling middleware
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

const PORT = process.env.PORT || 3005;
app.listen(PORT, '192.168.7.175', () => {
    console.log(`Server running on port ${PORT}`);
});  this code is working fine if i search keyowrd like karan , kabir , ankita ....means single keyowrd but when i saerch kabir singh or ankita yadav it is displaying all the files eithet having kabir or singh ....same for ankita yadav ....i want pdfs only those who have the seracehd keyowrd combined not alg alg