# FormData Empty Issue - FIXED ✅

## Problem Identified
The FormData was appearing empty at the backend because the `request.formData()` was being called INSIDE the permission wrapper (`withCreatePermission` / `withUpdatePermission`) rather than at the beginning of the route handler.

In Next.js, the request body can only be read ONCE. If any code reads the request stream before `formData()` is called, the stream is consumed and subsequent calls return empty data.

## Root Cause
```typescript
// ❌ WRONG - This structure was causing the issue
export async function POST(request: NextRequest) {
  return withCreatePermission(request, "tbl_student_registrations", async () => {
    // ... delay in reading formData
    const formData = await request.formData();  // By now, body might be consumed
  });
}
```

## Solution Applied
I've restructured both endpoints to parse FormData **IMMEDIATELY** at the start:

### 1. **POST /api/backend/students** - FIXED ✅
File: [src/app/api/backend/students/route.ts](src/app/api/backend/students/route.ts)

```typescript
// ✅ CORRECT - Parse formData FIRST
export async function POST(request: NextRequest) {
  // Step 1: Parse formData at the very beginning
  let formData: FormData;
  try {
    formData = await request.formData();
    console.log("✅ FormData parsed successfully");
  } catch (error: any) {
    return NextResponse.json(
      { success: false, message: "Failed to parse form data: " + error.message },
      { status: 400 }
    );
  }

  // Step 2: Check permissions after formData is parsed
  const permissionCheck = await requirePermission(request, "tbl_student_registrations", "create");
  if (permissionCheck) return permissionCheck;

  // Step 3: Now use formData in the handler
  const connection = await pool.getConnection();
  try {
    // ... rest of your logic
  } finally {
    connection.release();
  }
}
```

### 2. **PUT /api/backend/students/[id]** - FIXED ✅
File: [src/app/api/backend/students/\[id\]/route.ts](src/app/api/backend/students/%5Bid%5D/route.ts)

Same fix applied - FormData is now parsed before permission checks.

## Added Debug Logging
Both endpoints now include debug logging that will show:
- ✅ When FormData is successfully parsed
- 📋 All entries in FormData (fields and files)
- ❌ Any errors during parsing

**Console output example:**
```
✅ FormData parsed successfully
📋 FormData entries:
  student_registration_name: "John Doe"
  student_registration_email: "john@example.com"
  student_registration_phone: "03001234567"
  student_registration_matric_degree: File(transcript.pdf, size: 52341)
```

## Testing Steps

1. **Clear Browser Cache**
   ```
   Ctrl + Shift + Delete  (Windows)
   Cmd + Shift + Delete   (Mac)
   ```

2. **Test Create Student**
   - Open browser DevTools (F12)
   - Go to Console tab
   - Try creating a new student
   - You should see the debug logs with FormData entries
   - If empty, you'll see an error message

3. **Test Update Student**
   - Edit an existing student
   - Check console logs again
   - You should see all the form data being sent

4. **Check Network Tab**
   - Network tab → POST/PUT request
   - Request Payload should show FormData with all fields

## What Changed

| File | Change |
|------|--------|
| [src/app/api/backend/students/route.ts](src/app/api/backend/students/route.ts) | Parse FormData first, then check permissions |
| [src/app/api/backend/students/\[id\]/route.ts](src/app/api/backend/students/%5Bid%5D/route.ts) | Same restructuring for PUT method |

## Debug Logging (Can Be Removed Later)

Once you confirm the issue is fixed, you can remove these debug logs:

```typescript
// 🔍 DEBUG LOGGING - Remove after fixing
console.log("✅ FormData parsed successfully");
console.log("📋 FormData entries:");
for (const [key, value] of formData.entries()) {
  if (value instanceof File) {
    console.log(`  ${key}: File(${value.name}, size: ${value.size})`);
  } else {
    console.log(`  ${key}: ${value}`);
  }
}
```

## Why This Fixes The Issue

1. **Request body is read at the right time** - Before any async operations that might interfere
2. **No stream consumption** - FormData is parsed immediately, before permission checks
3. **Error handling** - Errors during FormData parsing are caught and reported
4. **Backwards compatible** - The rest of your logic remains unchanged

## Next Steps

1. **Test the fix** with the steps above
2. **Check console logs** to verify FormData is being received
3. **Monitor for errors** - any FormData parsing issues will be logged
4. **Remove debug logs** once confirmed working in production

## If Issue Persists

If FormData is still empty after these changes:

1. Check [DEBUG_GUIDE.md](DEBUG_GUIDE.md) for additional debugging steps
2. Verify the Content-Type header is `multipart/form-data` in the Network tab
3. Check that the frontend FormData is being created correctly (see DEBUG_GUIDE.md for frontend logging)

## References

- [Next.js Request object documentation](https://nextjs.org/docs/app/api-reference/functions/next-request)
- [FormData API](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
- [Multipart form data in Node.js](https://nodejs.org/en/docs/guides/nodejs-file-upload/)
