import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

export async function POST(req: NextRequest) {
    // Only allow in development
    if (process.env.NODE_ENV === 'production') {
        return NextResponse.json({ error: 'This route is disabled in production.' }, { status: 403 });
    }

    try {
        const body = await req.json();

        // Ensure we are in the project root by using process.cwd()
        // Path: <project-root>/remotion/session.json
        const remotionDir = path.join(process.cwd(), 'remotion');
        const filePath = path.join(remotionDir, 'session.json');

        // Create remotion directory if it doesn't exist
        if (!fs.existsSync(remotionDir)) {
            fs.mkdirSync(remotionDir, { recursive: true });
        }

        // Write the JSON file
        fs.writeFileSync(filePath, JSON.stringify(body, null, 2), 'utf-8');

        return NextResponse.json({ success: true, path: filePath });
    } catch (error: any) {
        console.error('Failed to save session:', error);
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}
