// src/auth.ts
import NextAuth from "next-auth";
import Google from "next-auth/providers/google";
import { PrismaClient } from "@/app/generated/prisma";
async function generateRegisterCode(): Promise<string> {
  // Library-free random (Edge 호환). 16바이트 hex
  let out = "";
  for (let i = 0; i < 16; i++) {
    const byte = Math.floor(Math.random() * 256);
    out += byte.toString(16).padStart(2, "0");
  }
  return out;
}

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Google({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),

  ],
  // callbacks 제거: 세션에 registerCode를 포함하지 않음
  
  events: {
    async signIn({ user, account, profile }) {
      // Upsert User (by email)
      try {
        const prisma = new PrismaClient();
        const email = user?.email ?? "";
        if (!email) {
          console.warn("[NextAuth] Missing email, skip user upsert");
          return;
        }

        const existing = await prisma.user.findFirst({ where: { email } });
        if (existing) {
          const registerCodeData = existing.RegisgerCode
            ? {}
            : { RegisgerCode: await generateRegisterCode() };
          await prisma.user.update({
            where: { id: existing.id },
            data: {
              icon: (user as any)?.image ?? existing.icon,
              ...registerCodeData,
            },
          });
        } else {
          await prisma.user.create({
            data: {
              email,
              icon: (user as any)?.image ?? "",
              RegisgerCode: await generateRegisterCode(),
            },
          });
        }
        await prisma.$disconnect();
      } catch (e) {
        console.error("[NextAuth] User upsert failed", e);
      }
    },
  },
});