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

const prisma = new PrismaClient();

export const POST: RequestHandler = async ({ request, cookies }) => {
  const { passwort } = await request.json();

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

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

  cookies.set('admin_session', 'true', {
    path: '/',
    httpOnly: true,
    sameSite: 'strict',
    maxAge: 60 * 60 * 4 // 4 Stunden
  });

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