import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { hashPassword } from "@/lib/auth";

export async function POST(req: Request) {
    try {
        const count = await prisma.globalSettings.count();
        if (count > 0) {
            return NextResponse.json({ message: "Settings already initialized" }, { status: 200 });
        }

        const body = await req.json().catch(() => ({}));
        const passwordFromBody = typeof body?.password === "string" ? body.password : "";
        const passwordFromEnv = process.env.INIT_DEFAULT_PASSWORD || "";
        const initPassword = passwordFromBody || passwordFromEnv;

        if (!initPassword || initPassword.length < 6) {
            return NextResponse.json(
                { error: "Missing init password. Provide body.password or INIT_DEFAULT_PASSWORD (min 6 chars)." },
                { status: 400 }
            );
        }

        const initToken = process.env.INIT_SETUP_TOKEN;

        if (initToken) {
            const providedToken = req.headers.get("x-init-token");
            if (providedToken !== initToken) {
                return NextResponse.json({ error: "Invalid init token" }, { status: 401 });
            }
        }

        const hashedPassword = await hashPassword(initPassword);
        await prisma.globalSettings.create({
            data: {
                id: "default",
                password: hashedPassword,
            },
        });

        return NextResponse.json({ message: "Initialized default settings" }, { status: 201 });
    } catch (error) {
        console.error("Init Settings Error:", error);
        return NextResponse.json({ error: "Failed to initialize settings" }, { status: 500 });
    }
}
