'use server';

import { redirect } from 'next/navigation';
import { isAdminAuthenticated, getAdminUser, verifyPassword, hashPassword, createOrUpdateAdminUser } from '@/lib/adminAuth';

export async function changeAdminPassword(formData: FormData) {
  const isAuthenticated = await isAdminAuthenticated();
  if (!isAuthenticated) redirect('/admin/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('/admin/change-password?error=missing_fields');
  }

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

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

  // Get current admin user from database
  const dbAdmin = await getAdminUser();

  // Verify current password
  let isValid = false;
  if (dbAdmin) {
    isValid = await verifyPassword(currentPassword, dbAdmin.passwordHash);
  } else {
    // Fall back to env vars if no database entry
    isValid = currentPassword === process.env.ADMIN_PASSWORD;
  }

  if (!isValid) {
    redirect('/admin/change-password?error=invalid_current');
  }

  // Update or create admin user with new password
  const hashedPassword = await hashPassword(newPassword);
  const username = dbAdmin?.username ?? process.env.ADMIN_USER ?? 'admin';
  await createOrUpdateAdminUser(username, hashedPassword);

  redirect('/admin/dashboard?success=password_changed');
}
