// src/app/api/download/route.ts

import { NextRequest, NextResponse } from 'next/server';
import { auth } from "@/auth";
import { getFileNodeById } from "@/data-access/file-nodes";
import { getOneDriveContentStream } from "@/services/onedrive";

export async function GET(request: NextRequest) {
  try {
    // 1. Authenticate the user session
    const session = await auth();
    if (!session?.user?.id) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    // 2. Extract parameters from URL
    const { searchParams } = new URL(request.url);
    const fileId = searchParams.get('id');
    const mode = searchParams.get('mode') === 'inline' ? 'inline' : 'attachment';

    if (!fileId) {
      return new NextResponse("File ID is required", { status: 400 });
    }

    // 3. DAL: Fetch file metadata from local database
    const fileNode = await getFileNodeById(fileId);

    if (!fileNode || !fileNode.oneDriveId) {
      return new NextResponse("File not found", { status: 404 });
    }

    // 4. SERVICE: Get the binary stream from Microsoft Graph
    // The service layer automatically handles the 'getFreshAccessToken' logic
    const graphResponse = await getOneDriveContentStream(session.user.id, fileNode.oneDriveId);

    // 5. Stream the response directly to the client
    // We pass the graphResponse.body (ReadableStream) directly to NextResponse
   // src/app/api/download/route.ts
const metadata = fileNode.metadata as any;
const contentType = metadata?.mimeType || 'application/octet-stream';

return new NextResponse(graphResponse.body, {
  status: 200,
  headers: {
    'Content-Type': contentType,
    'Content-Disposition': `${mode}; filename="${encodeURIComponent(fileNode.name)}"`,
  },
});

  } catch (error: any) {
    console.error('Download Route Error:', error);
    return new NextResponse(
      JSON.stringify({ error: "Internal Server Error", message: error.message }), 
      { status: 500 }
    );
  }
}