'use server';

import { cookies } from 'next/headers';
import {
  getCurrentUser,
  hashPassword,
  verifyPassword,
  deleteOtherSessions,
} from '@/lib/auth';
import { prisma } from '@/lib/prisma';

/**
 * Change the current user's password.
 *
 * Requires the current password (defends against a stolen-session
 * attacker rotating the password to lock the real owner out). Always
 * revokes every other session for this user — if you're rotating
 * because you suspect compromise, the worst-case kicks the attacker
 * off immediately.
 */
export async function changePasswordAction(
  currentPassword: string,
  newPassword: string,
  newPasswordConfirm: string,
): Promise<{ success?: true; error?: string; revoked?: number }> {
  try {
    const user = await getCurrentUser();
    if (!user) return { error: 'Not signed in.' };

    if (newPassword.length < 8) {
      return { error: 'New password must be at least 8 characters.' };
    }
    if (newPassword !== newPasswordConfirm) {
      return { error: 'New password and confirmation do not match.' };
    }
    if (currentPassword === newPassword) {
      return { error: 'New password must differ from current password.' };
    }

    const ok = await verifyPassword(currentPassword, user.passwordHash);
    if (!ok) {
      return { error: 'Current password is incorrect.' };
    }

    const newHash = await hashPassword(newPassword);
    await prisma.user.update({
      where: { id: user.id },
      data: { passwordHash: newHash },
    });

    const cookieStore = await cookies();
    const currentToken = cookieStore.get('sessionToken')?.value ?? null;
    const revoked = await deleteOtherSessions(user.id, currentToken);

    return { success: true, revoked };
  } catch (err) {
    console.error('changePassword error:', err);
    return { error: 'An error occurred while changing your password.' };
  }
}
