import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma";
import jwt from "jsonwebtoken";
import bcrypt from "bcryptjs";
import { z } from "zod/v4"; 

const schema = z.object({
    token: z.string(),
    old_password: z.string(),
    password: z.string().min(8, "Password must be at least 8 characters long").max(32, "Password must be at most 32 characters long").regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/, "Password must contain at least one lowercase letter, one uppercase letter, one digit, and one special character"),
});

export async function POST(request: NextRequest) {
    try {
        const body = schema.parse(await request.json());

        if(!process.env.JWT_SECRET) {
            return NextResponse.json({ error: "No JWT secret found" }, { status: 500 });
        }

        const decoded = jwt.verify(body.token, process.env.JWT_SECRET) as { id: string };

        const user = await prisma.user.findUnique({
            where: {
                id: decoded.id,
            },
        });

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

        const validPassword = await bcrypt.compare(body.old_password, user.password);

        if (!validPassword) {
            return NextResponse.json({ error: "Invalid password" }, { status: 401 });
        }

        const hashedPassword = await bcrypt.hash(body.password, 10);

        await prisma.user.update({
            where: {
                id: decoded.id,
            },
            data: {
                password: hashedPassword,
            },
        });

        return NextResponse.json({ message: "Password updated successfully" }, { status: 200 });
    } catch (error: any) {
        if(error instanceof z.ZodError) {
            return NextResponse.json({ error: error.issues[0].message }, { status: 400 });
        }
        return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
}

