import { d as defineEventHandler, u as useLogger, z as parseMultipartFormData, a as readBody, B as validateEvent, w as publicSettings, c as createError, D as findOrCreatePlace, G as setEventMedia, E as Event, H as findOrCreateTags, J as sign, v as eventToAP, K as secretSettings, x as notifyEvent, q as mapEvent } from '../../nitro/nitro.mjs';
import { g as getUser } from '../../_/getUser.mjs';
import { z } from 'zod';
import 'luxon';
import '@sequelize/core';
import 'html-to-text';
import 'crypto';
import 'node:fs';
import 'sharp';
import 'path';
import 'node:stream';
import 'jsdom';
import 'dompurify';
import 'mime-types';
import 'fs';
import 'fs/promises';
import 'linkify-html';
import '@peertube/http-signature';
import 'jsonld';
import 'lodash.intersection';
import 'email-templates';
import 'node:http';
import 'node:https';
import 'node:crypto';
import 'node:events';
import 'node:buffer';
import 'node:path';
import 'vue';
import 'vue-router';
import 'dotenv';
import 'url';
import 'bcryptjs';
import 'slugify';
import 'umzug';
import 'consola';
import '@sequelize/core/decorators-legacy';
import 'util';
import 'mitt';
import 'ical.js';
import 'node:url';
import 'fast-xml-parser';
import '../../_/jwt.mjs';
import 'jose';

const index_post = defineEventHandler(async (evt) => {
  const log = useLogger("New event");
  const user = await getUser(evt);
  const multiPartBody = await parseMultipartFormData(evt);
  const jsonBody = await readBody(evt);
  let eventPayload;
  try {
    eventPayload = validateEvent(publicSettings, user).parse(multiPartBody || jsonBody);
  } catch (e) {
    log.warn(e);
    const message = e instanceof z.ZodError ? e.issues[0]?.message : String(e);
    throw createError({ statusCode: 400, message });
  }
  let place;
  if (eventPayload.place) {
    place = await findOrCreatePlace(eventPayload.place).catch((e) => {
      log.warn(e);
      throw createError({ statusCode: 400, message: String(e) });
    });
    eventPayload.placeId = place?.id;
  }
  const media = await setEventMedia(eventPayload);
  if (media) {
    eventPayload.media = [media];
  }
  const event = await Event.create(eventPayload).catch((e) => {
    throw createError({ statusCode: 500, message: e.message });
  });
  let tags = [];
  if (eventPayload.tags) {
    tags = await findOrCreateTags(eventPayload.tags);
    await event.setTags(tags);
  }
  if (event?.recurrent && event.is_visible) ; else {
    if (publicSettings.enable_federation) {
      try {
        event.ld_signature = await sign(eventToAP(event), secretSettings.privateKey, `${publicSettings.baseurl}/federation/u/${publicSettings.instance_name}#main-key`);
        await event.save({ silent: true });
      } catch (e) {
        log.warn("Error signing Event ", e);
      }
    }
    notifyEvent("Create", event.id);
  }
  return mapEvent(event, { place, tags, user });
});

export { index_post as default };
