import { readFile } from "node:fs/promises";
import path from "node:path";
import { NextResponse } from "next/server";
import { getDbPool } from "@/db";
import { getSession } from "@/lib/auth";
import { isClientSession } from "@/lib/authorization";

export const runtime = "nodejs";

const contentTypes: Record<string, string> = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };

export async function GET() {
  const session = await getSession();
  if (!session || !isClientSession(session) || !session.tenantId) return NextResponse.json({ error: "Não autenticado." }, { status: 401 });
  try {
    const [rows] = await getDbPool().execute("SELECT logo_storage_key FROM tenant_branding WHERE tenant_id = ? LIMIT 1", [session.tenantId]);
    const storageKey = String((rows as { logo_storage_key?: string | null }[])[0]?.logo_storage_key || "");
    if (!storageKey) return NextResponse.json({ error: "Logo não configurado." }, { status: 404 });
    const root = path.resolve(process.env.STORAGE_PATH || "/app/storage"); const filePath = path.resolve(root, storageKey);
    if (!filePath.startsWith(`${root}${path.sep}`)) return NextResponse.json({ error: "Arquivo inválido." }, { status: 400 });
    return new NextResponse(await readFile(filePath), { headers: { "Content-Type": contentTypes[path.extname(filePath).toLowerCase()] || "application/octet-stream", "Cache-Control": "private, max-age=300" } });
  } catch {
    return NextResponse.json({ error: "Não foi possível carregar o logo." }, { status: 404 });
  }
}
