import { NextResponse } from 'next/server';
import { head } from '@vercel/blob';
import path from 'path';
import fs from 'fs';
// Check if we're in local development mode
const IS_LOCAL_DEV = !process.env.BLOB_READ_WRITE_TOKEN;
const LOCAL_STORAGE_DIR = path.join(process.cwd(), '.devdoc-storage');
/**
 * Asset proxy - serves uploaded assets for multi-tenant docs
 * 
 * GET /api/assets/[slug]/[...path]
 * 
 * This allows MDX files to reference assets as:
 *   ![logo](/api/assets/my-project/logo.png)
 * 
 * Or with the middleware rewrite, simply:
 *   ![logo](/logo.png)  -> rewrites to /api/assets/[slug]/logo.png
 */ export async function GET(request, { params }) {
    try {
        const { path: pathSegments } = await params;
        if (!pathSegments || pathSegments.length < 2) {
            return NextResponse.json({
                error: 'Invalid asset path'
            }, {
                status: 400
            });
        }
        // First segment is the project slug, rest is the asset path
        const [slug, ...assetPath] = pathSegments;
        const fileName = assetPath.join('/');
        if (!slug || !fileName) {
            return NextResponse.json({
                error: 'Missing slug or file path'
            }, {
                status: 400
            });
        }
        // Build blob path
        const blobPath = `projects/${slug}/assets/${fileName}`;
        if (IS_LOCAL_DEV) {
            // Local development - serve from filesystem
            const filePath = path.join(LOCAL_STORAGE_DIR, 'projects', slug, 'assets', fileName);
            if (!fs.existsSync(filePath)) {
                return NextResponse.json({
                    error: 'Asset not found'
                }, {
                    status: 404
                });
            }
            const fileBuffer = fs.readFileSync(filePath);
            const contentType = getContentType(fileName);
            return new NextResponse(fileBuffer, {
                status: 200,
                headers: {
                    'Content-Type': contentType,
                    'Cache-Control': 'public, max-age=31536000, immutable'
                }
            });
        }
        // Production - fetch from Vercel Blob
        const blobInfo = await head(blobPath).catch(()=>null);
        if (!blobInfo) {
            return NextResponse.json({
                error: 'Asset not found'
            }, {
                status: 404
            });
        }
        // Redirect to the blob URL (more efficient than proxying)
        return NextResponse.redirect(blobInfo.url, {
            status: 302,
            headers: {
                'Cache-Control': 'public, max-age=31536000, immutable'
            }
        });
    } catch (error) {
        console.error('[Asset Proxy] Error:', error);
        return NextResponse.json({
            error: 'Failed to serve asset'
        }, {
            status: 500
        });
    }
}
/**
 * Get content type from file extension
 */ function getContentType(fileName) {
    const ext = fileName.split('.').pop()?.toLowerCase();
    const types = {
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'png': 'image/png',
        'gif': 'image/gif',
        'webp': 'image/webp',
        'svg': 'image/svg+xml',
        'ico': 'image/x-icon',
        'pdf': 'application/pdf',
        'mp4': 'video/mp4',
        'webm': 'video/webm',
        'mp3': 'audio/mpeg',
        'wav': 'audio/wav',
        'woff': 'font/woff',
        'woff2': 'font/woff2',
        'ttf': 'font/ttf',
        'otf': 'font/otf'
    };
    return types[ext || ''] || 'application/octet-stream';
}
