'use server';

import { redirect } from 'next/navigation';
import { getCurrentCustomer, verifyPassword, hashPassword } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function changePassword(formData: FormData) {
  const customer = await getCurrentCustomer();
  if (!customer) redirect('/account/login');

  const currentPassword = String(formData.get('currentPassword') ?? '');
  const newPassword = String(formData.get('newPassword') ?? '');
  const confirmPassword = String(formData.get('confirmPassword') ?? '');

  // Validate
  if (!currentPassword || !newPassword || !confirmPassword) {
    redirect('/account/change-password?error=missing_fields');
  }

  if (newPassword.length < 8) {
    redirect('/account/change-password?error=password_too_short');
  }

  if (newPassword !== confirmPassword) {
    redirect('/account/change-password?error=passwords_dont_match');
  }

  // Verify current password
  const isValid = await verifyPassword(currentPassword, customer.passwordHash);
  if (!isValid) {
    redirect('/account/change-password?error=invalid_current');
  }

  // Update password
  const hashedPassword = await hashPassword(newPassword);
  await prisma.customer.update({
    where: { id: customer.id },
    data: { passwordHash: hashedPassword },
  });

  redirect('/account?success=password_changed');
}
