import "server-only";
import { db } from "./db";

/** Finds where a media URL is used. Used to warn before deleting. */
export async function mediaUsage(url: string) {
  const like = `%${url}%`;
  const [products, cats, cols, posts, sections, settings] = await Promise.all([
    db.productImage.findMany({ where: { url }, select: { product: { select: { id: true, name: true } } } }),
    db.category.findMany({ where: { OR: [{ imageUrl: url }, { hoverUrl: url }] }, select: { name: true } }),
    db.collection.findMany({ where: { imageUrl: url }, select: { title: true } }),
    db.editorialPost.findMany({ where: { OR: [{ coverUrl: url }] }, select: { title: true } }),
    db.$queryRaw<{ label: string }[]>`SELECT \`label\` FROM \`HomepageSection\` WHERE CAST(\`draftData\` AS CHAR) LIKE ${like} OR CAST(\`publishedData\` AS CHAR) LIKE ${like}`,
    db.$queryRaw<{ key: string }[]>`SELECT \`key\` FROM \`Setting\` WHERE CAST(\`value\` AS CHAR) LIKE ${like}`,
  ]);
  const postGallery = await db.$queryRaw<{ title: string }[]>`SELECT \`title\` FROM \`EditorialPost\` WHERE CAST(\`gallery\` AS CHAR) LIKE ${like}`;
  return [
    ...products.map((p) => `Product: ${p.product.name}`), ...cats.map((c) => `Category: ${c.name}`), ...cols.map((c) => `Collection: ${c.title}`),
    ...posts.map((p) => `Journal: ${p.title}`), ...postGallery.map((p) => `Journal gallery: ${p.title}`), ...sections.map((s) => `Homepage: ${s.label}`), ...settings.map((s) => `Settings: ${s.key}`),
  ];
}
