// /opt/erp-system/app/api/portal/password/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";

export async function PUT(request: Request) {
  const session = await getServerSession(authOptions);
  if (!session || (session.user as any).userType !== 'CUSTOMER') {
    return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
  }

  try {
    const body = await request.json();
    if (!body.password || body.password.length < 6) {
      return NextResponse.json({ error: 'Passwort zu kurz' }, { status: 400 });
    }

    const hash = await bcrypt.hash(body.password, 10);
    const customerId = parseInt((session.user as any).id);

    await prisma.customer.update({
      where: { id: customerId },
      data: { passwordHash: hash, forcePasswordChange: false }
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: 'Fehler beim Speichern' }, { status: 500 });
  }
}
