import { y as defineEventHandler, X as get, b0 as useLogger, aG as readValidatedBody, aj as isHiddenService, v as createError, Y as getActor, a2 as getInstance, W as followActor } from '../../../nitro/nitro.mjs';
import { z } from 'zod';
import { r as requireAdminSession } from '../../../_/session.mjs';
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 '../../../_/getUser.mjs';
import '../../../_/jwt.mjs';
import 'jose';

const schema = z.object({
  url: z.string()
});
const add_trust_post = defineEventHandler(async (event) => {
  const config = get();
  await requireAdminSession(event);
  const log = useLogger("add trust");
  const body = await readValidatedBody(event, schema.parse);
  let url = body.url.trim();
  let instance;
  if (!url.startsWith("http") && url.includes("@")) {
    const [user, instance_url] = url.replace(/^@/, "").split("@");
    log.debug("Adds user: %s and instance: %s because url was: %s", user, instance_url, url);
    try {
      let protocol = "https://";
      if (config.hidden_service === "true" && isHiddenService(url)) {
        protocol = "http://";
      }
      if (config.hidden_service !== "true" && isHiddenService(url)) {
        log.warn("Trying to trust instance %s but hidden services are not enabled", instance_url);
        throw createError({ status: 403, message: "Hidden service not allowed" });
      }
      const webfinger = await $fetch(`${protocol}${instance_url}/.well-known/webfinger?resource=acct:${user}@${instance_url}`);
      if (webfinger && Array.isArray(webfinger?.links)) {
        const actor_url = webfinger.links.find((l) => l.rel === "self");
        if (!actor_url) {
          log.warn("Cannot found `self` links in webfinger of %s", url);
          throw createError({ status: 404, message: "No self links in webfinger" });
        }
        log.info(`Adding trusted instance ${instance_url} and actor ${actor_url.href}...`);
        const actor = await getActor(actor_url.href, true);
        if (!actor) {
          log.warn("Cannot found actor %s", actor_url.href);
          throw createError({ status: 404, message: "No actor found" });
        }
        log.debug("Actor %s", actor.ap_id);
        await actor.update({ trusted: true });
        return actor;
      }
    } catch (e) {
      log.error("Wrong webfinger response from %s: %s ", url, e?.response?.data ?? String(e));
      throw createError({ status: 404, message: "Wrong webfinger response" });
    }
  }
  try {
    if (!url.startsWith("http")) {
      url = `https://${url}`;
    }
    url = url.replace(/\/$/, "");
    log.info(`Adding trusted instance ${url} ...`);
    instance = await getInstance(url, true);
    if (!instance) {
      throw createError({ status: 404, message: "No instance" });
    }
    let actor;
    try {
      log.debug("Trying to use %s as actor", url);
      actor = await getActor(url);
      if (actor) {
        log.debug("Actor %s", actor.ap_id);
        await actor.update({ trusted: true });
        await followActor(actor);
        return actor;
      } else {
        log.error("not an actor? ");
      }
    } catch (e) {
      log.debug("%s is probably not an actor: %s", url, String(e));
    }
    if (!actor && instance?.applicationActor) {
      log.debug("This node supports FEP-2677 and applicationActor is: %s", instance.applicationActor);
      actor = await getActor(instance.applicationActor, true);
      if (!actor) {
        log.debug("applicationActor %s is probably not an actor", instance.applicationActor);
        throw createError({ status: 404, message: "Actor not found" });
      }
      log.debug("Actor %s", actor.ap_id);
      await actor.update({ trusted: true });
      return actor;
    }
    log.debug(`instance .well-known: ${instance.name} - ${instance.domain}`);
    if (instance.actor) {
      const instance_hostname = new URL(url).host;
      const webfinger = await $fetch(`${url}/.well-known/webfinger?resource=acct:${instance.actor}@${instance_hostname}`);
      if (!webfinger?.links) {
        throw createError({ status: 404, message: "No links in webfinger" });
      }
      const actorURL = webfinger?.links.find((l) => l.rel === "self").href;
      const actor2 = await getActor(actorURL, true);
      await actor2.update({ trusted: true });
      return actor2;
    }
    throw createError({ statusCode: 404, statusMessage: "No way" });
  } catch (e) {
    console.error(e);
    log.error("Error adding trusted actor %s", e?.response?.data ?? String(e));
    throw createError({ statusCode: 404, statusMessage: "Error adding trusted actor" });
  }
});

export { add_trust_post as default };
