import { NextRequest, NextResponse } from "next/server";
import { auth } from "../../../../auth";
import fs from "fs/promises";
import path from "path";

const ALLOWED_PAGES = ["home", "vodic", "lokacija", "okolina"];

function contentPath(page: string) {
  return path.join(process.cwd(), "content", "pages", `${page}.json`);
}

export async function GET(req: NextRequest) {
  const page = req.nextUrl.searchParams.get("page");
  if (!page || !ALLOWED_PAGES.includes(page)) {
    return NextResponse.json({ error: "Invalid page" }, { status: 400 });
  }
  const raw = await fs.readFile(contentPath(page), "utf-8");
  return NextResponse.json(JSON.parse(raw));
}

export async function POST(req: NextRequest) {
  const session = await auth();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { page, content } = await req.json();
  if (!page || !ALLOWED_PAGES.includes(page)) {
    return NextResponse.json({ error: "Invalid page" }, { status: 400 });
  }
  if (!content || typeof content !== "object") {
    return NextResponse.json({ error: "Invalid content" }, { status: 400 });
  }

  await fs.writeFile(contentPath(page), JSON.stringify(content, null, 2), "utf-8");
  return NextResponse.json({ ok: true });
}
