import { NextResponse } from 'next/server';
import { put } from '@vercel/blob';
import { validateApiKey } from '@/lib/storage/blob';
import path from 'path';
import fs from 'fs';
// Max file size: 25MB
const MAX_FILE_SIZE = 25 * 1024 * 1024;
// Allowed file types for assets
const ALLOWED_TYPES = [
    'image/jpeg',
    'image/png',
    'image/gif',
    'image/webp',
    'image/svg+xml',
    'image/x-icon',
    'image/vnd.microsoft.icon',
    'application/pdf',
    'video/mp4',
    'video/webm',
    'audio/mpeg',
    'audio/wav',
    'font/woff',
    'font/woff2',
    'font/ttf',
    'font/otf',
    'application/font-woff',
    'application/font-woff2'
];
// 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');
/**
 * Upload asset API - receives files from CLI and stores in Vercel Blob
 * 
 * POST /api/assets/upload
 * Headers:
 *   Authorization: Bearer <api_key>
 *   Content-Type: multipart/form-data
 * Body: FormData with:
 *   - file: File to upload
 *   - slug: Project slug
 *   - path: Optional path/filename for the asset
 */ export async function POST(request) {
    try {
        // Validate API key
        const authHeader = request.headers.get('Authorization');
        const apiKey = authHeader?.replace('Bearer ', '');
        if (!apiKey) {
            return NextResponse.json({
                error: 'API key required. Provide via Authorization header.'
            }, {
                status: 401
            });
        }
        const validatedSlug = await validateApiKey(apiKey);
        if (!validatedSlug) {
            return NextResponse.json({
                error: 'Invalid API key'
            }, {
                status: 403
            });
        }
        // Parse multipart form data
        const formData = await request.formData();
        const file = formData.get('file');
        const slug = formData.get('slug');
        const assetPath = formData.get('path');
        if (!file) {
            return NextResponse.json({
                error: 'No file provided'
            }, {
                status: 400
            });
        }
        if (!slug) {
            return NextResponse.json({
                error: 'Project slug is required'
            }, {
                status: 400
            });
        }
        // Verify the API key matches the project
        if (validatedSlug !== slug) {
            return NextResponse.json({
                error: 'API key does not match project'
            }, {
                status: 403
            });
        }
        // Validate file size
        if (file.size > MAX_FILE_SIZE) {
            return NextResponse.json({
                error: `File size exceeds maximum allowed size of 25MB. Current size: ${(file.size / (1024 * 1024)).toFixed(2)}MB`
            }, {
                status: 400
            });
        }
        // Validate file type
        const contentType = file.type;
        if (!ALLOWED_TYPES.includes(contentType) && !contentType.startsWith('image/')) {
            return NextResponse.json({
                error: `File type "${contentType}" is not allowed. Allowed types: images, PDFs, videos, audio, and fonts.`
            }, {
                status: 400
            });
        }
        // Generate asset path
        const fileName = assetPath || file.name;
        const sanitizedFileName = fileName.replace(/[^a-zA-Z0-9._-]/g, '_');
        const blobPath = `projects/${slug}/assets/${sanitizedFileName}`;
        // Get file buffer
        const buffer = Buffer.from(await file.arrayBuffer());
        // Store in local filesystem or Vercel Blob
        let url;
        if (IS_LOCAL_DEV) {
            // Local development - store in filesystem
            const assetDir = path.join(LOCAL_STORAGE_DIR, 'projects', slug, 'assets');
            fs.mkdirSync(assetDir, {
                recursive: true
            });
            const filePath = path.join(assetDir, sanitizedFileName);
            fs.writeFileSync(filePath, buffer);
            url = `file://${filePath}`;
        } else {
            // Production - store in Vercel Blob
            const blob = await put(blobPath, buffer, {
                access: 'public',
                contentType,
                allowOverwrite: true
            });
            url = blob.url;
        }
        return NextResponse.json({
            success: true,
            url,
            path: blobPath,
            fileName: sanitizedFileName,
            size: file.size,
            contentType
        });
    } catch (error) {
        console.error('[Asset Upload API] Error:', error);
        const message = error instanceof Error ? error.message : String(error);
        return NextResponse.json({
            error: 'Upload failed',
            details: message
        }, {
            status: 500
        });
    }
}
/**
 * OPTIONS for CORS preflight
 */ export async function OPTIONS() {
    return new NextResponse(null, {
        status: 200,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type, Authorization'
        }
    });
}
