import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { hashPassword, verifyPassword } from "@/lib/auth";
import { requireApiAuth } from "@/lib/api-auth";

export async function PUT(req: Request) {
    const authError = await requireApiAuth();
    if (authError) return authError;

    try {
        const { currentPassword, newPassword } = await req.json().catch(() => ({}));
        if (typeof currentPassword !== "string" || currentPassword.length === 0) {
            return NextResponse.json({ error: "Invalid current password" }, { status: 400 });
        }
        if (typeof newPassword !== "string" || newPassword.length < 6) {
            return NextResponse.json({ error: "New password must be at least 6 characters" }, { status: 400 });
        }
        if (newPassword === currentPassword) {
            return NextResponse.json({ error: "New password must be different" }, { status: 400 });
        }

        const settings = await prisma.globalSettings.findUnique({
            where: { id: "default" },
        });

        if (!settings) {
            return NextResponse.json({ error: "Settings not found" }, { status: 404 });
        }

        const isValid = await verifyPassword(currentPassword, settings.password);
        if (!isValid) {
            return NextResponse.json({ error: "Current password incorrect" }, { status: 401 });
        }

        const hashedPassword = await hashPassword(newPassword);

        await prisma.globalSettings.update({
            where: { id: "default" },
            data: { password: hashedPassword },
        });

        return NextResponse.json({ success: true });
    } catch {
        return NextResponse.json({ error: "Failed to change password" }, { status: 500 });
    }
}
