// /opt/erp-system/app/api/tickets/[id]/attachments/route.ts
import { NextResponse } from 'next/server';
import prisma from '../../../../../lib/prisma';
import { getServerSession } from "next-auth/next";
import { authOptions } from "../../../auth/[...nextauth]/route";
import { writeFile, readFile } from 'fs/promises';
import { join } from 'path';

const UPLOAD_DIR = join(process.cwd(), 'uploads');

// POST: Datei hochladen
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });

  try {
    const params = await context.params;
    const ticketId = parseInt(params.id);
    const formData = await request.formData();
    
    const file = formData.get('file') as File;
    if (!file) return NextResponse.json({ error: 'Keine Datei gefunden' }, { status: 400 });

    const bytes = await file.arrayBuffer();
    const buffer = Buffer.from(bytes);

    // Dateinamen bereinigen und eindeutig machen
    const safeOriginalName = file.name.replace(/[^a-zA-Z0-9.-]/g, '_');
    const savedName = `${Date.now()}-${safeOriginalName}`;
    const filepath = join(UPLOAD_DIR, savedName);

    await writeFile(filepath, buffer);

    const attachment = await prisma.attachment.create({
      data: {
        fileName: file.name,
        savedName: savedName,
        fileSize: file.size,
        fileType: file.type,
        ticketId: ticketId
      }
    });

    return NextResponse.json(attachment, { status: 201 });
  } catch (error) {
    console.error("Upload Fehler:", error);
    return NextResponse.json({ error: 'Fehler beim Upload' }, { status: 500 });
  }
}

// GET: Datei-Liste abrufen oder einzelne Datei herunterladen
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session) return new NextResponse('Nicht autorisiert', { status: 401 });

  const { searchParams } = new URL(request.url);
  const downloadId = searchParams.get('download');

  try {
    const params = await context.params;
    const ticketId = parseInt(params.id);

    // Modus 1: Einzelne Datei herunterladen
    if (downloadId) {
      const attachment = await prisma.attachment.findUnique({
        where: { id: parseInt(downloadId) }
      });

      if (!attachment || attachment.ticketId !== ticketId) {
        return new NextResponse('Datei nicht gefunden', { status: 404 });
      }

      const filepath = join(UPLOAD_DIR, attachment.savedName);
      const fileBuffer = await readFile(filepath);

      return new NextResponse(fileBuffer, {
        headers: {
          'Content-Type': attachment.fileType,
          'Content-Disposition': `attachment; filename="${attachment.fileName}"`
        }
      });
    }

    // Modus 2: Liste aller Anhänge des Tickets zurückgeben
    const attachments = await prisma.attachment.findMany({
      where: { ticketId: ticketId },
      orderBy: { createdAt: 'desc' }
    });
    return NextResponse.json(attachments);

  } catch (error) {
    return new NextResponse('Fehler beim Abrufen der Datei', { status: 500 });
  }
}
