// /opt/erp-system/app/api/settings/route.ts
import { NextResponse } from 'next/server';
import prisma from '../../../lib/prisma';
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('SYSTEM_SETTINGS');
}

export async function GET() {
  try {
    let settings = await prisma.systemSettings.findFirst({ where: { id: 1 } });
    if (!settings) {
      settings = await prisma.systemSettings.create({ data: { id: 1 } });
    }
    
    // Passwörter nicht ans Frontend senden
    const { smtpPass, imapPass, ...safeSettings } = settings;
    
    return NextResponse.json({
      ...safeSettings,
      hasSmtpPass: !!smtpPass,
      hasImapPass: !!imapPass
    });
  } catch (error) {
    return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
  }
}

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

  try {
    const body = await request.json();
    
    const updateData: any = {
      hourlyRate: parseFloat(body.hourlyRate),
      taxRate: parseFloat(body.taxRate),
      companyName: body.companyName,
      companyInfo: body.companyInfo,
      smtpHost: body.smtpHost,
      smtpPort: parseInt(body.smtpPort) || 587,
      smtpUser: body.smtpUser,
      smtpFrom: body.smtpFrom,
      imapHost: body.imapHost,
      imapPort: parseInt(body.imapPort) || 993,
      imapUser: body.imapUser,
    };

    if (body.smtpPass && body.smtpPass.trim() !== '') updateData.smtpPass = body.smtpPass;
    if (body.imapPass && body.imapPass.trim() !== '') updateData.imapPass = body.imapPass;

    const updated = await prisma.systemSettings.upsert({
      where: { id: 1 },
      update: updateData,
      create: { id: 1, ...updateData }
    });
    
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Update-Fehler' }, { status: 500 });
  }
}
