import { promises as fs } from "fs";
import path from "path";

export async function DELETE(req) {
  try {
    const { filePath } = await req.json();

    if (!filePath || typeof filePath !== "string") {
      return new Response(JSON.stringify({ error: "Invalid or missing file path" }), {
        status: 400,
      });
    }

    if (filePath.includes("..")) {
      return new Response(JSON.stringify({ error: "Invalid path" }), {
        status: 400,
      });
    }

    // 🔥 Strip out `api/files/` prefix if it exists
    const safePath = filePath.replace(/^api\/files\//, "");

    // 🔁 Adjust path to point to uploads folder
    const fullPath = path.join(process.cwd(), "uploads", safePath);

    await fs.unlink(fullPath);

    return new Response(JSON.stringify({ message: "File deleted successfully" }), {
      status: 200,
    });
  } catch (err) {
    console.error("File deletion failed:", err);
    return new Response(JSON.stringify({ error: err.message }), { status: 500 });
  }
}



// import { promises as fs } from 'fs';
// import path from 'path';

// export async function DELETE(req) {
//   try {
//     const { filePath } = await req.json();

//     if (!filePath || typeof filePath !== 'string') {
//       return new Response(JSON.stringify({ error: 'Invalid or missing file path' }), {
//         status: 400,
//       });
//     }

//     // Prevent directory traversal
//     if (filePath.includes('..')) {
//       return new Response(JSON.stringify({ error: 'Invalid path' }), {
//         status: 400,
//       });
//     }

//     // Build full path based on new upload directory
//     const fullPath = path.join(process.cwd(), 'uploads', filePath);

//     await fs.unlink(fullPath);

//     return new Response(JSON.stringify({ message: 'File deleted successfully' }), { status: 200 });
//   } catch (err) {
//     return new Response(JSON.stringify({ error: err.message }), { status: 500 });
//   }
// }
