import { db } from '@/lib/db';
import { createResponse, handleApiError } from '@/src/lib/api';
import bcrypt from 'bcryptjs';
import { hash } from 'crypto';

export async function POST(req: Request, { params }: { params: Promise<{ token: string }> }) {
  try {
    const { token } = await params;
    const { password } = await req.json();

    const resetToken = await db.resetToken.findUnique({ where: { token: hash('sha256', token) } });
    if (!resetToken) {
      return createResponse(404, 'Invalid reset link');
    }

    const tokenExpirationDate = new Date(resetToken.expiresAt);
    const currentDateUtc = new Date(new Date().toISOString());
    if (tokenExpirationDate < currentDateUtc) {
      return createResponse(400, 'Reset link expired');
    }

    const hashedPassword = await bcrypt.hash(password, 10);
    await db.user.update({ where: { id: resetToken.userId }, data: { password: hashedPassword } });
    return createResponse(200, 'Password updated successfully');
  } catch (error) {
    return handleApiError(error);
  }
}
