// /opt/erp-system/app/api/customers/[id]/route.ts
import { NextResponse } from 'next/server';
import prisma from '../../../../lib/prisma';
import bcrypt from 'bcryptjs';
import { getServerSession } from "next-auth/next";
import { authOptions } from "../../auth/[...nextauth]/route";

async function getPerms() {
  const session = await getServerSession(authOptions);
  if (!session) return null;
  return (session.user as any)?.permissions || [];
}

export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
  const perms = await getPerms();
  if (!perms) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });

  try {
    const params = await context.params;
    const customer = await prisma.customer.findUnique({
      where: { id: parseInt(params.id) },
      include: { 
        contacts: { orderBy: { createdAt: 'desc' } },
        tickets: { orderBy: { createdAt: 'desc' } },
        contracts: { orderBy: { createdAt: 'desc' } },
        documents: { orderBy: { createdAt: 'desc' } },
        credentials: { orderBy: { createdAt: 'desc' } }
      }
    });
    
    if (!customer) return NextResponse.json({ error: 'Nicht gefunden' }, { status: 404 });
    return NextResponse.json(customer);
  } catch (error) {
    console.error('Customer GET Error:', error);
    return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
  }
}

export async function PUT(request: Request, context: { params: Promise<{ id: string }> }) {
  const perms = await getPerms();
  if (!perms || (!perms.includes('CUSTOMERS_MANAGE') && !perms.includes('CUSTOMERS_EDIT'))) {
    return NextResponse.json({ error: 'Keine Berechtigung zum Bearbeiten von Kundendaten' }, { status: 403 });
  }

  try {
    const params = await context.params;
    const body = await request.json();
    
    const updateData: any = {
      companyName: body.companyName,
      firstName: body.firstName,
      lastName: body.lastName,
      email: body.email,
      phone: body.phone,
      address: body.address,
      zipCode: body.zipCode,
      city: body.city,
      additionalEmails: body.additionalEmails || [],
    };

    // Nur ein neues Passwort hashen und speichern, wenn das Feld ausgefüllt wurde
    if (body.password && body.password.trim() !== '') {
      updateData.passwordHash = await bcrypt.hash(body.password, 10);
    }

    const customer = await prisma.customer.update({
      where: { id: parseInt(params.id) },
      data: updateData,
      include: { contacts: true }
    });
    
    return NextResponse.json(customer);
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Update fehlgeschlagen' }, { status: 500 });
  }
}

