"use server";

import { db } from "@/db";
import { users, households } from "@/db/schema";
import bcrypt from "bcryptjs";
import { eq } from "drizzle-orm";
import { redirect } from "next/navigation";
import { signIn } from "@/auth";
import { seedHouseholdDefaults } from "@/lib/seed";
import { z } from "zod";

const SignupSchema = z.object({
  name: z.string().min(1).max(80),
  email: z.string().email().toLowerCase().trim(),
  password: z.string().min(8).max(200),
});

export async function signupAction(formData: FormData) {
  const parsed = SignupSchema.parse({
    name: formData.get("name"),
    email: formData.get("email"),
    password: formData.get("password"),
  });

  const [existing] = await db.select().from(users).where(eq(users.email, parsed.email));
  if (existing) throw new Error("Email already registered");

  const passwordHash = await bcrypt.hash(parsed.password, 10);

  const [household] = await db
    .insert(households)
    .values({ name: `${parsed.name}'s household` })
    .returning();

  await db.insert(users).values({
    name: parsed.name,
    email: parsed.email,
    passwordHash,
    householdId: household.id,
    role: "owner",
  });

  await seedHouseholdDefaults(household.id);

  await signIn("credentials", {
    email: parsed.email,
    password: parsed.password,
    redirect: false,
  });
  redirect("/onboarding");
}
