import NextAuth, { DefaultSession } from 'next-auth'
import GitHub from 'next-auth/providers/github'
import Google from 'next-auth/providers/google'

import { storeUser } from '@/app/actions'

// override type definitions for session
declare module 'next-auth' {
  interface Session {
    user: {
      id?: string | null | undefined
    } & DefaultSession['user']
  }
}

export const {
  handlers: { GET, POST },
  auth
} = NextAuth({
  providers: [
    Google,
  ],

  // ✅ 加这一行，信任所有 Host，彻底解决动态部署报错问题
  trustHost: true,

  // ✅ 加这一行，防止缺失 secret 报错
  secret: 'hardcoded-super-secret-key-please-change',
  
  callbacks: {
    async jwt({ token, profile }) {
      if (profile?.id) {
        token.id = String(profile.id)
        const user = {
          ...token,
          ...profile,
          id: String(profile.id)
        }
        await storeUser(user)
      }
      return token
    },

    async session({ session, token }) {
      if (token?.id) {
        session.user.id = String(token.id)
      }
      return session
    }
    },
    pages: {
      signIn: '/sign-in'
    }
    
})
