// /opt/erp-system/app/api/users/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 checkAccess() {
  const session = await getServerSession(authOptions);
  const perms = (session?.user as any)?.permissions || [];
  return perms.includes('TEAM_MANAGE');
}

export async function GET() {
  try {
    const users = await prisma.user.findMany({
      include: { role: true },
      orderBy: { createdAt: 'asc' },
    });
    
    const safeUsers = users.map(u => ({ 
      id: u.id, firstName: u.firstName, lastName: u.lastName, email: u.email, role: u.role, createdAt: u.createdAt, roleId: u.roleId 
    }));
    return NextResponse.json(safeUsers);
  } catch (error) {
    return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  if (!await checkAccess()) return NextResponse.json({ error: 'Zugriff verweigert' }, { status: 403 });

  try {
    const body = await request.json();
    const passwordHash = await bcrypt.hash(body.password, 10);

    const newUser = await prisma.user.create({
      data: {
        firstName: body.firstName,
        lastName: body.lastName,
        email: body.email,
        passwordHash: passwordHash,
        roleId: parseInt(body.roleId),
      },
      include: { role: true }
    });

    return NextResponse.json({ 
      id: newUser.id, firstName: newUser.firstName, email: newUser.email, role: newUser.role 
    }, { status: 201 });
  } catch (error: any) {
    if (error.code === 'P2002') return NextResponse.json({ error: 'E-Mail wird bereits verwendet.' }, { status: 400 });
    return NextResponse.json({ error: 'Fehler beim Erstellen' }, { status: 500 });
  }
}

export async function PUT(request: Request) {
  if (!await checkAccess()) return NextResponse.json({ error: 'Zugriff verweigert' }, { status: 403 });

  try {
    const body = await request.json();
    
    // Basis-Daten für das Update
    const updateData: any = {
      firstName: body.firstName,
      lastName: body.lastName,
      email: body.email,
      roleId: parseInt(body.roleId)
    };

    // Passwort nur aktualisieren, wenn ein neues eingegeben wurde
    if (body.password && body.password.trim() !== '') {
      updateData.passwordHash = await bcrypt.hash(body.password, 10);
    }

    const updatedUser = await prisma.user.update({
      where: { id: body.id },
      data: updateData,
      include: { role: true }
    });

    return NextResponse.json({ 
      id: updatedUser.id, firstName: updatedUser.firstName, email: updatedUser.email, role: updatedUser.role 
    }, { status: 200 });
  } catch (error: any) {
    if (error.code === 'P2002') return NextResponse.json({ error: 'E-Mail wird bereits verwendet.' }, { status: 400 });
    return NextResponse.json({ error: 'Fehler beim Aktualisieren' }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  const session = await getServerSession(authOptions);
  const perms = (session?.user as any)?.permissions || [];
  if (!perms.includes('DATA_DELETE')) return NextResponse.json({ error: 'Keine Löschberechtigung' }, { status: 403 });

  try {
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');
    if (!id) return NextResponse.json({ error: 'ID fehlt' }, { status: 400 });

    const userId = parseInt(id);

    // Unassign tickets instead of deleting them
    await prisma.ticket.updateMany({ where: { assignedToId: userId }, data: { assignedToId: null } });
    // Delete user's time entries and notes
    await prisma.timeEntry.deleteMany({ where: { userId } });
    await prisma.ticketNote.deleteMany({ where: { userId } });

    await prisma.user.delete({ where: { id: userId } });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
  }
}
