import { json } from '@sveltejs/kit';
import fs from 'fs/promises';
import path from 'path';

const OLD_PLIST_PASSWORD = 'mivancicus';
const NEW_PLIST_PASSWORD = 'neleakeldnagyontitkosjelszo';
const PEAROO_PASSWORD = 'PEAROOAKEDVENCMACSKAM';

async function getLoginPairs() {
    try {
        const loginHandlerPath = path.join(process.cwd(), 'src', 'routes', 'api', 'login', '+server.js');
        const content = await fs.readFile(loginHandlerPath, 'utf-8');

        const pairs = [];
        
        const matches = content.matchAll(/if\s*\(username\s*===\s*['"]([^'"]+)['"]\s*&&\s*(?:password\s*===\s*['"]([^'"]+)['"]|hashedPassword\s*===\s*adminHash)/g);
        
        for (const match of matches) {
            const username = match[1];
            const password = username === 'admin' ? 'admin' : match[2];
            
            if (username && password) {
                pairs.push({ username, password });
            }
        }

        return pairs;
    } catch (error) {
        console.error('Error reading login pairs:', error);
        return [];
    }
}

export async function POST({ request }) {
    const { password } = await request.json();

    if (password === NEW_PLIST_PASSWORD ) {
        const pairs = await getLoginPairs();
        return json({
            success: true,
            pairs
        });
    }
    else if (password === OLD_PLIST_PASSWORD || password === PEAROO_PASSWORD) {
        const pairs = await getLoginPairs();
        return json({
            success: true,
            html: `
                <div style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
                    <p style="color: #e74c3c; font-size: 1.5rem; margin-bottom: 0.5rem;">ejnyebejnye!</p>
                    <p style="color: #e74c3c;">ez a jelszó már korábban leakelve lett.</p>
                </div>
            `
        });
    }

    return json({
        success: false,
        message: 'Invalid password'
    });
}