import { NextRequest, NextResponse } from 'next/server';
import { previewDocumentLibraryVersion } from '@/features/foundation/document-library/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

type Params = { params: Promise<{ id: string }> };

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmDocumentLibraryRead
    });
    const { object } = await previewDocumentLibraryVersion({
      versionId: id,
      organizationId: organization.id,
      userId: session.user.id
    });

    return new NextResponse(object.body, {
      headers: {
        'Content-Type': object.contentType,
        'Content-Disposition': `inline; filename="${object.fileName}"`
      }
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json(
      { message: 'Unable to preview document library version' },
      { status: 500 }
    );
  }
}
