'use server';

import { revalidatePath } from 'next/cache';
import { requireAdmin } from '@/lib/auth/current-user';
import { signupSchema, slugify } from '@/lib/validation/signup';
import { getUserByEmail, createTenantWithOwner, slugDisponible } from '@/db/auth-queries';
import { setUserStatus } from '@/db/admin-queries';
import { hashPassword } from '@/lib/auth/password';

export async function crearReformista(_prev: string | null, formData: FormData): Promise<string | null> {
  await requireAdmin();
  const parsed = signupSchema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) return parsed.error.issues[0]?.message ?? 'Datos no válidos.';
  const data = parsed.data;
  if (await getUserByEmail(data.email)) return 'Ya existe una cuenta con ese email.';

  let slug = slugify(data.empresa);
  let n = 1;
  while (!(await slugDisponible(slug))) slug = `${slugify(data.empresa)}-${++n}`;

  await createTenantWithOwner({
    nombreEmpresa: data.empresa,
    slug,
    provincia: data.provincia,
    email: data.email,
    passwordHash: await hashPassword(data.password),
    nombre: data.nombre,
  });
  revalidatePath('/admin/usuarios');
  return null;
}

export async function toggleUsuario(formData: FormData) {
  await requireAdmin();
  const userId = String(formData.get('userId'));
  const next = String(formData.get('next')) as 'activo' | 'deshabilitado';
  await setUserStatus(userId, next);
  revalidatePath('/admin/usuarios');
}
