import { NextResponse } from 'next/server';
import { ListObjectsV2Command } from "@aws-sdk/client-s3";
import s3Client, { BUCKET_NAME } from '@/lib/s3';

export async function GET(
  request: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;

    // Check credentials exist so it doesn't crash locally
    if (!process.env.STORAGE_ACCESS_KEY_ID) {
      console.warn("[API] S3/GCS Storage credentials missing, returning empty list");
      return NextResponse.json({ success: true, files: [], count: 0 });
    }

    const command = new ListObjectsV2Command({
      Bucket: BUCKET_NAME,
      Prefix: `projects/${projectId}/`,
      MaxKeys: 100,
    });

    const response = await s3Client.send(command);
    
    const fileList = (response.Contents || []).map(file => ({
      name: file.Key?.split('/').pop() || file.Key,
      fullPath: file.Key,
      size: file.Size,
      timeCreated: file.LastModified,
      updated: file.LastModified,
    }));

    return NextResponse.json({
      success: true,
      files: fileList,
      count: fileList.length,
    });
  } catch (error) {
    console.error('[API] Error fetching S3/GCS storage files:', error);
    return NextResponse.json(
      { error: 'Failed to fetch storage files' },
      { status: 500 }
    );
  }
}
