import { NextRequest, NextResponse } from 'next/server';
import { PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import s3Client, { BUCKET_NAME } from '@/lib/s3';

// Instead of handling raw binary files directly through the Next.js API route (which is slow and memory-heavy),
// we return a secure Presigned URL. The frontend then uploads the file directly to S3/GCS.
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const body = await request.json();

    const { filename, contentType } = body;

    if (!filename) {
      return NextResponse.json(
        { error: 'filename is required' },
        { status: 400 }
      );
    }

    if (!process.env.STORAGE_ACCESS_KEY_ID) {
       return NextResponse.json(
         { error: 'Storage is not configured on this server.' },
         { status: 500 }
       );
    }

    const fileKey = `projects/${projectId}/documents/${Date.now()}_${filename.replace(/[^a-zA-Z0-9.-]/g, '_')}`;

    const command = new PutObjectCommand({
      Bucket: BUCKET_NAME,
      Key: fileKey,
      ContentType: contentType || 'application/octet-stream'
    });

    // Generate a URL that is valid for 15 minutes for the client to upload the file to
    const uploadUrl = await getSignedUrl(s3Client, command, { expiresIn: 900 });

    return NextResponse.json({
      success: true,
      uploadUrl: uploadUrl,
      fileKey: fileKey,
      message: 'Presigned URL generated successfully. Send a PUT request with the file binary to this URL.'
    });

  } catch (error) {
    console.error('Error generating upload URL:', error);
    return NextResponse.json(
      { error: 'Failed to generate upload URL', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}
