import { prisma } from "@/lib/db";
import bcrypt from "bcryptjs";

// One-time setup endpoint — creates the admin user and default settings.
// Disable or remove this route after first use in production.
export async function POST(req: Request) {
  const setupKey = req.headers.get("x-setup-key");
  if (setupKey !== process.env.SETUP_KEY) {
    return Response.json({ error: "Forbidden" }, { status: 403 });
  }

  try {
    const existing = await prisma.adminUser.findFirst();
    if (existing) {
      return Response.json({ error: "Admin already exists" }, { status: 409 });
    }

    const { username, password } = await req.json();
    if (!username || !password || password.length < 8) {
      return Response.json({ error: "Username and password (min 8 chars) required" }, { status: 400 });
    }

    const hashed = await bcrypt.hash(password, 12);
    const user = await prisma.adminUser.create({ data: { username, password: hashed } });

    await prisma.siteSettings.upsert({
      where: { id: "main" },
      create: {
        id: "main",
        siteTitle: "Ali Taghavi",
        description: "Founder, builder, and strategist based in Tehran.",
        currentStatus: "در حال ساخت HyperAccount — زیرساخت هویت برای محصولات ایرانی",
        socialGithub: "https://github.com/alitaghavi",
        socialLinkedin: "https://linkedin.com/in/alitaghavi",
        socialTelegram: "https://t.me/alitaghavi",
      },
      update: {},
    });

    return Response.json({ success: true, userId: user.id });
  } catch (err) {
    console.error("[setup]", err);
    return Response.json({ error: "Server error" }, { status: 500 });
  }
}
