import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { uploadFileToR2 } from '@/lib/r2';
import { env } from '@/lib/env';
import { db } from '@/lib/db';

export async function POST(request: NextRequest) {
    try {
        // 1. Authentication Check
        const session = await getServerSession(authOptions);
        let userId = session?.user?.id;

        // Fallback: Check for simple-login cookie if no NextAuth session
        if (!userId) {
            const cookieUserId = request.cookies.get('userId')?.value;
            if (cookieUserId) {
                // Verify user exists
                const user = await db.user.findUnique({
                    where: { id: cookieUserId },
                    select: { id: true }
                });
                if (user) {
                    userId = user.id;
                }
            }
        }

        if (!userId) {
            return new NextResponse('Unauthorized', { status: 401 });
        }

        // 2. Parse Form Data
        const formData = await request.formData();
        const file = formData.get('file') as File | null;

        if (!file) {
            return NextResponse.json(
                { error: 'No file provided' },
                { status: 400 }
            );
        }

        // 3. Validation
        // Check file size (default 10MB)
        const MAX_SIZE = parseInt(env.MAX_UPLOAD_SIZE || '10485760');
        if (file.size > MAX_SIZE) {
            return NextResponse.json(
                { error: `File too large. Maximum size: ${MAX_SIZE / 1024 / 1024}MB` },
                { status: 400 }
            );
        }

        // Check file type (allow images and PDFs)
        const allowedTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'];
        if (!allowedTypes.includes(file.type)) {
            return NextResponse.json(
                { error: 'Invalid file type. Only PDF and Images are allowed.' },
                { status: 400 }
            );
        }

        // 4. Upload to R2
        const buffer = Buffer.from(await file.arrayBuffer());
        const publicUrl = await uploadFileToR2(buffer, file.name, file.type);

        // 5. Success
        return NextResponse.json({
            success: true,
            url: publicUrl,
            filename: file.name,
            type: file.type
        });

    } catch (error) {
        console.error('Upload error:', error);
        return NextResponse.json(
            { error: 'Internal server error during upload' },
            { status: 500 }
        );
    }
}
