import type { RequestHandler } from './$types';
import bcrypt from 'bcryptjs';
import { prisma } from '$lib/prisma';

export const POST: RequestHandler = async ({ request, cookies }) => {
  try {
    const adminRecord = await prisma.admin.findUnique({ where: { id: 1 } });
    
    if (!adminRecord?.password) {
      return new Response(JSON.stringify({ message: 'Admin password not found' }), { status: 500 });
    }

    const { passwort } = await request.json();

    if (!passwort) {
      return new Response(JSON.stringify({ message: 'Passwort erforderlich' }), { status: 400 });
    }

    const isValid = await bcrypt.compare(passwort, adminRecord.password);

    if (isValid) {
      cookies.set('admin-auth', 'authenticated', {
        path: '/',
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'strict',
        maxAge: 60 * 60 * 24,
      });
      return new Response(JSON.stringify({ success: true }), { status: 200 });
    }
    
    return new Response(JSON.stringify({ message: 'Falsches Passwort' }), { status: 401 });
  } catch (error) {
    console.error('Login error:', error);
    return new Response(JSON.stringify({ message: 'Serverfehler' }), { status: 500 });
  }
};