import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient();

function checkAuth(cookies: any) {
  return cookies.get('admin_session') === 'true';
}

export const POST: RequestHandler = async ({ request, cookies }) => {
  if (!checkAuth(cookies)) return new Response('Nicht erlaubt', { status: 401 });

  const { oldPassword, newPassword } = await request.json();

  const admin = await prisma.admin.findUnique({ where: { id: 1 } });
  if (!admin) return json({ error: 'Admin nicht gefunden' }, { status: 500 });

  const isValid = await bcrypt.compare(oldPassword, admin.password);
  if (!isValid) return json({ error: 'Falsches Passwort' }, { status: 401 });

  const newHashed = await bcrypt.hash(newPassword, 10);
  await prisma.admin.update({
    where: { id: 1 },
    data: { password: newHashed }
  });

  return json({ success: true });
};