import { hashPassword } from "@/lib/auth/password";
import { findByUsername, createUser } from "@/lib/db/repos/usersRepo";
import { createDefaults } from "@/lib/db/repos/rateLimitRepo";

let seeded = false;

export async function seedAdmin() {
  if (seeded) return;
  seeded = true;

  try {
    const existingAdmin = await findByUsername("admin");
    if (existingAdmin) return;
  } catch {
    // Table might not exist yet on first boot — skip
    return;
  }

  const initialPassword = process.env.INITIAL_PASSWORD;
  if (!initialPassword) {
    console.warn("[seedAdmin] No INITIAL_PASSWORD set — admin user not auto-created");
    return;
  }

  try {
    const passwordHash = hashPassword(initialPassword);
    const admin = await createUser("admin", passwordHash);

    // Override role and approval via direct update
    const { findById, updateRole, updateApproval } = await import("@/lib/db/repos/usersRepo");
    await updateRole(admin.id, "admin");
    await updateApproval(admin.id, true);

    await createDefaults(admin.id);

    console.log("[seedAdmin] Admin user created from INITIAL_PASSWORD");
  } catch (error) {
    console.error("[seedAdmin] Failed to create admin:", error.message);
  }
}
