"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const index$2 = require("./user-v6mfWQ2d.cjs");
const getInstalledAppPath = require("./getInstalledAppPath-3c7mqtrk.cjs");
const throwIfNotHaveAdminAccessToTeam = require("./throwIfNotHaveAdminAccessToTeam-OTNj--da.cjs");
const z = require("zod");
const httpError = require("./http-error-mkY8Ke7V.cjs");
const getAppKeysFromSlug = require("./getAppKeysFromSlug-W8EkKxxV.cjs");
const _metadata = require("./_metadata-kMCX19xv.cjs");
async function handler$2(req, res) {
  if (!req.session?.user?.id) {
    return res.status(401).json({ message: "You must be logged in to do this" });
  }
  const userId = req.session.user.id;
  const appType = "giphy_other";
  const teamId = Number(req.query.teamId);
  const credentialOwner = req.query.teamId ? { teamId } : { userId: req.session.user.id };
  await throwIfNotHaveAdminAccessToTeam.throwIfNotHaveAdminAccessToTeam({ teamId: teamId ?? null, userId });
  try {
    const alreadyInstalled = await index$2.prisma.credential.findFirst({
      where: {
        type: appType,
        ...credentialOwner
      }
    });
    if (alreadyInstalled) {
      throw new Error("Already installed");
    }
    const installation = await index$2.prisma.credential.create({
      data: {
        type: appType,
        key: {},
        ...credentialOwner,
        appId: "giphy"
      }
    });
    if (!installation) {
      throw new Error("Unable to create user credential for giphy");
    }
  } catch (error) {
    if (error instanceof Error) {
      return res.status(500).json({ message: error.message });
    }
    return res.status(500);
  }
  return res.status(200).json({ url: getInstalledAppPath.getInstalledAppPath({ variant: "other", slug: "giphy" }) });
}
const checkGiphyApiKey = async () => {
  const appKeys = await getAppKeysFromSlug.getAppKeysFromSlug("giphy");
  if (typeof appKeys.api_key === "string")
    return appKeys.api_key;
  throw new httpError.HttpError({ statusCode: 400, message: "Missing Giphy api_key" });
};
const searchGiphy = async (locale, keyword, offset = 0) => {
  const apiKey = await checkGiphyApiKey();
  const queryParams = new URLSearchParams({
    api_key: apiKey,
    q: keyword,
    limit: "1",
    offset: String(offset),
    // Contains images that are broadly accepted as appropriate and commonly witnessed by people in a public environment.
    rating: "g",
    lang: locale
  });
  const response = await fetch(`https://api.giphy.com/v1/gifs/search?${queryParams.toString()}`, {
    method: "GET",
    headers: {
      Accept: "application/json"
    }
  });
  const responseBody = await response.json();
  const gifs = responseBody.data;
  return {
    gifImageUrl: gifs?.[0]?.images?.fixed_height_downsampled?.url || null,
    total: responseBody.pagination.total_count
  };
};
const getGiphyById = async (giphyId) => {
  const apiKey = await checkGiphyApiKey();
  const queryParams = new URLSearchParams({
    api_key: apiKey
  });
  const response = await fetch(`https://api.giphy.com/v1/gifs/${giphyId}?${queryParams.toString()}`, {
    method: "GET",
    headers: {
      Accept: "application/json"
    }
  });
  const responseBody = await response.json();
  const gifs = responseBody.data;
  return gifs?.images?.fixed_height_downsampled?.url || null;
};
const giphyManager = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  getGiphyById,
  searchGiphy
}, Symbol.toStringTag, { value: "Module" }));
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  GiphyManager: giphyManager
}, Symbol.toStringTag, { value: "Module" }));
const searchSchema = z.z.object({
  keyword: z.z.string(),
  offset: z.z.number().min(0)
});
async function handler$1(req, res) {
  const userId = req.session?.user?.id;
  if (!userId) {
    return res.status(401).json({ message: "You must be logged in to do this" });
  }
  try {
    const user = await index$2.prisma.user.findFirst({
      where: {
        id: userId
      },
      select: {
        id: true,
        locale: true
      }
    });
    const locale = user?.locale || "en";
    const { keyword, offset } = req.body;
    const { gifImageUrl, total } = await searchGiphy(locale, keyword, offset);
    return res.status(200).json({
      image: gifImageUrl,
      // rotate results to 0 offset when no more gifs
      nextOffset: total === offset + 1 ? 0 : offset + 1
    });
  } catch (error) {
    if (error instanceof Error) {
      return res.status(500).json({ message: error.message });
    }
    return res.status(500);
  }
}
function validate$1(handler2) {
  return async (req, res) => {
    if (req.method === "POST") {
      try {
        searchSchema.parse(req.body);
      } catch (error) {
        if (error instanceof z.ZodError && error?.name === "ZodError") {
          return res.status(400).json(error?.issues);
        }
        return res.status(402);
      }
    } else {
      return res.status(405);
    }
    await handler2(req, res);
  };
}
const search = validate$1(handler$1);
const giphyUrlRegexp = new RegExp("^https://(.*).giphy.com/media/(.*)/giphy.gif(.*)");
const getSchema = z.z.object({
  url: z.z.string().regex(giphyUrlRegexp, "Giphy URL is invalid")
});
async function handler(req, res) {
  const userId = req.session?.user?.id;
  if (!userId) {
    return res.status(401).json({ message: "You must be logged in to do this" });
  }
  try {
    const { url } = req.body;
    const parsedUrl = new URL(url.replace(/ /g, ""));
    const sanitisedUrl = parsedUrl.origin + parsedUrl.pathname;
    const matches = giphyUrlRegexp.exec(sanitisedUrl);
    if (!matches || matches.length < 3) {
      return res.status(400).json({ message: "Giphy URL is invalid" });
    }
    const giphyId = matches[2];
    const gifImageUrl = await getGiphyById(giphyId);
    return res.status(200).json({ image: gifImageUrl });
  } catch (error) {
    console.error({ error });
    if (error instanceof Error) {
      return res.status(500).json({ message: error.message });
    }
    return res.status(500);
  }
}
function validate(handler2) {
  return async (req, res) => {
    if (req.method === "POST") {
      try {
        getSchema.parse(req.body);
      } catch (error) {
        if (error instanceof z.ZodError && error?.name === "ZodError") {
          return res.status(400).json(error?.issues);
        }
        return res.status(402);
      }
    } else {
      return res.status(405);
    }
    await handler2(req, res);
  };
}
const get = validate(handler);
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add: handler$2,
  get,
  search
}, Symbol.toStringTag, { value: "Module" }));
exports.metadata = _metadata.metadata;
exports.api = index;
exports.lib = index$1;
