'use server';

import { redirect } from 'next/navigation';
import { eq } from 'drizzle-orm';
import { db } from '@/db';
import { tenants } from '@/db/schema';
import { signupSchema, slugify } from '@/lib/validation/signup';
import { getUserByEmail, createTenantWithOwner, slugDisponible } from '@/db/auth-queries';
import { hashPassword } from '@/lib/auth/password';
import { createSession } from '@/lib/auth/session';

const TRIAL_MS = 14 * 24 * 60 * 60 * 1000;

export async function signup(_prev: string | null, formData: FormData): Promise<string | null> {
  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}`;

  const passwordHash = await hashPassword(data.password);
  const { tenant, user } = await createTenantWithOwner({
    nombreEmpresa: data.empresa,
    slug,
    provincia: data.provincia,
    email: data.email,
    passwordHash,
    nombre: data.nombre,
  });

  await db
    .update(tenants)
    .set({ trialEndsAt: new Date(Date.now() + TRIAL_MS) })
    .where(eq(tenants.id, tenant.id));

  await createSession(user.id);
  redirect('/panel');
}
