'use server';

import { redirect } from 'next/navigation';
import { getUserByEmail } from '@/db/auth-queries';
import { verifyPassword } from '@/lib/auth/password';
import { createSession } from '@/lib/auth/session';

export async function login(_prev: string | null, formData: FormData): Promise<string | null> {
  const email = String(formData.get('email') ?? '').trim().toLowerCase();
  const password = String(formData.get('password') ?? '');
  if (!email || !password) return 'Introduce email y contraseña.';

  const user = await getUserByEmail(email);
  if (!user || user.status !== 'activo') return 'Credenciales incorrectas.';
  if (!(await verifyPassword(password, user.passwordHash))) return 'Credenciales incorrectas.';

  await createSession(user.id);
  redirect(user.role === 'admin' ? '/admin' : '/panel');
}
