import "server-only";
import { eq } from "drizzle-orm";
import { db, schema } from "@/lib/db";
import { auth } from "@/lib/auth";

/**
 * Crée un compte client avec mot de passe défini directement (pas de magic
 * link), puis renvoie l'userId.
 *
 * Better Auth a `disableSignUp: true` côté API publique, donc on contourne
 * en faisant les inserts manuellement avec le hash de password fourni par
 * `auth.$context.password.hash()`.
 *
 * Si l'email existe déjà : on retourne l'userId existant SANS toucher au
 * mot de passe (le client peut récupérer son compte via /forgot-password).
 */
export async function createClientAccount(input: {
  email: string;
  password: string;
  name: string;
}): Promise<
  | { ok: true; userId: string; isNew: boolean }
  | { ok: false; error: string }
> {
  const email = input.email.toLowerCase().trim();
  const password = input.password;
  const name = input.name.trim();

  if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) {
    return { ok: false, error: "Email invalide." };
  }
  if (!password || password.length < 10) {
    return {
      ok: false,
      error: "Mot de passe trop court (10 caractères minimum).",
    };
  }
  if (!name) {
    return { ok: false, error: "Nom requis." };
  }

  // Email déjà pris ?
  const existing = await db
    .select()
    .from(schema.user)
    .where(eq(schema.user.email, email))
    .limit(1);

  if (existing.length > 0) {
    // Cas : le client a déjà un compte (peut-être créé via un dossier
    // précédent). On retourne son userId sans toucher au password ; il
    // pourra utiliser /forgot-password si besoin.
    return { ok: true, userId: existing[0].id, isNew: false };
  }

  try {
    const ctx = await auth.$context;
    const hashed = await ctx.password.hash(password);

    const userId = crypto.randomUUID();
    await db.insert(schema.user).values({
      id: userId,
      email,
      name,
      emailVerified: false,
      role: "client",
    });

    await db.insert(schema.account).values({
      id: crypto.randomUUID(),
      userId,
      accountId: email,
      providerId: "credential",
      password: hashed,
    });

    return { ok: true, userId, isNew: true };
  } catch (err) {
    console.error("[createClientAccount] failed:", err);
    return { ok: false, error: "Création du compte échouée." };
  }
}
