import { NextResponse } from "next/server";
import { promises as fs } from "fs";
import path from "path";
import { prisma } from "../../../../lib/prisma";

export const dynamic = "force-dynamic";
export const revalidate = 0;

const DATA_DIR = path.join(process.cwd(), "prisma", "data");

const resolveLogoPath = (relativePath: string) => {
  const absolutePath = path.join(DATA_DIR, relativePath);
  if (!absolutePath.startsWith(DATA_DIR)) {
    throw new Error("Ungültiger Pfad.");
  }
  return absolutePath;
};

const getLogoSettings = async () => {
  const pathSetting = await prisma.setting.findUnique({
    where: { key: "app_logo_path" }
  });
  const typeSetting = await prisma.setting.findUnique({
    where: { key: "app_logo_type" }
  });

  if (!pathSetting?.value || !typeSetting?.value) {
    return null;
  }

  return { path: pathSetting.value, type: typeSetting.value };
};

export async function GET() {
  const settings = await getLogoSettings();
  if (!settings) {
    return NextResponse.json({ error: "Kein Logo vorhanden." }, { status: 404 });
  }

  try {
    const absolutePath = resolveLogoPath(settings.path);
    const file = await fs.readFile(absolutePath);
    return new NextResponse(file, {
      headers: {
        "Content-Type": settings.type,
        "Cache-Control": "no-store"
      }
    });
  } catch {
    return NextResponse.json({ error: "Logo konnte nicht geladen werden." }, { status: 404 });
  }
}

export async function HEAD() {
  const settings = await getLogoSettings();
  if (!settings) {
    return new NextResponse(null, { status: 404 });
  }

  return new NextResponse(null, {
    status: 200,
    headers: {
      "Content-Type": settings.type,
      "Cache-Control": "no-store"
    }
  });
}
