import { sequence } from 'astro/middleware';
import crypto from 'node:crypto';
import type { MiddlewareHandler } from 'astro';
import { logger } from '@util/log.ts';

const actionInternalServerError: MiddlewareHandler = async (context, next) => {
  let response = await next();

  if (response.status === 500 && context.url.pathname.startsWith('/_actions/')) {
    const json = await response.json();

    const errorCode = crypto
      .createHash('md5')
      .update(Date.now() + context.clientAddress)
      .digest('hex');
    logger.error(`${errorCode}: ${json.message}`);

    json.message = `Interner Fehler. Bitte versuch es erneut oder kontakiere einen Administrator.\nFehler Code: ${errorCode}`;

    response = new Response(JSON.stringify(json), {
      status: response.status,
      headers: response.headers,
      statusText: response.statusText
    });
  }

  return response;
};

export const onRequest = sequence(actionInternalServerError);
