import { DrizzleAdapter } from "@auth/drizzle-adapter";
import { db } from "@/server/db";
import {
  accounts,
  players,
  sessions,
  users,
  verificationTokens,
} from "@/server/db/schema";
import type { Adapter } from "next-auth/adapters";

export const CustomDrizzleAdapter: Adapter = {
  ...(DrizzleAdapter(db, {
    usersTable: users as any,
    accountsTable: accounts,
    sessionsTable: sessions,
    verificationTokensTable: verificationTokens,
  }) as Adapter),

  async createUser(rawUser) {
    // Insert user **without** the image field
    const [user] = await db
      .insert(users)
      .values({
        name: rawUser.name,
        email: rawUser.email,
        emailVerified: rawUser.emailVerified,
      })
      .returning();
    if (!user) throw new Error("Error creating user");

    await db.insert(players).values({
      id: user.id,
      displayName: rawUser.name,
      avatar: rawUser.image,
    });
    return user;
  },
};
