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

export async function GET({ request, url }) {
    const authHeader = request.headers.get('x-auth');
    const imageName = url.searchParams.get('image');
    
    if (!imageName || !['skelly.jpg', 'klima.png', 'p1.png', 'p2.png', 'milka.jpg', '9s.gif', 'menczer.jpg', 'tomcica.webp', 'petiszivem.jpg', 'sodinazi.png'].includes(imageName)) {
        throw redirect(307, '/');
    }

    const validAuth = {
        'skelly.jpg': 'skelly-authenticated',
        'klima.png': 'klima-authenticated',
        'p1.png': 'pearoo-authenticated',
        'p2.png': 'pearoo-authenticated',
        'milka.jpg': 'milka-authenticated',
        '9s.gif': '9suw9suw9-authenticated',
        'menczer.jpg': 'menczer-authenticated',
        'tomcica.webp': 'tomcat-authenticated',
        'petiszivem.jpg': 'arad-authenticated',
        'sodinazi.png': 'sodika-authenticated'
    };

    if (!authHeader || authHeader !== validAuth[imageName]) {
        throw redirect(307, '/');
    }

    try {
        const imagePath = path.join(process.cwd(), 'src', 'lib', 'protected', imageName);
        
        const imageBuffer = await fs.readFile(imagePath);
        
        let contentType;
        if (imageName.endsWith('.jpg')) {
            contentType = 'image/jpeg';
        } else if (imageName.endsWith('.png')) {
            contentType = 'image/png';
        } else if (imageName.endsWith('.gif')) {
            contentType = 'image/gif';
        } else if (imageName.endsWith('.webp')) {
            contentType = 'image/webp';
        } else {
            contentType = 'application/octet-stream';
        }
        
        return new Response(imageBuffer, {
            headers: {
                'Content-Type': contentType,
                'Cache-Control': 'no-store, must-revalidate',
                'Pragma': 'no-cache'
            }
        });
    } catch (err) {
        throw error(404, 'Image not found');
    }
} 