import { NextAuthOptions } from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { prisma } from './prisma'
import bcrypt from 'bcryptjs'

declare module 'next-auth' {
  interface Session {
    user: {
      id: string
      name: string
      email: string
      role: string
      plan: string
      credits: number
      oabNumber?: string | null
      oabState?: string | null
      avatar?: string | null
    }
  }

  interface User {
    id: string
    name: string
    email: string
    role: string
    plan: string
    credits: number
    oabNumber?: string | null
    oabState?: string | null
    avatar?: string | null
  }
}

declare module 'next-auth/jwt' {
  interface JWT {
    id: string
    role: string
    plan: string
    credits: number
    oabNumber?: string | null
    oabState?: string | null
  }
}

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      name: 'credentials',
      credentials: {
        email: { label: 'Email', type: 'email' },
        password: { label: 'Senha', type: 'password' },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          throw new Error('Email e senha são obrigatórios')
        }

        const user = await prisma.user.findUnique({
          where: { email: credentials.email },
        })

        if (!user) {
          throw new Error('Usuário não encontrado')
        }

        const isPasswordValid = await bcrypt.compare(credentials.password, user.password)

        if (!isPasswordValid) {
          throw new Error('Senha incorreta')
        }

        return {
          id: user.id,
          name: user.name,
          email: user.email,
          role: user.role,
          plan: user.plan,
          credits: user.credits,
          oabNumber: user.oabNumber,
          oabState: user.oabState,
          avatar: user.avatar,
        }
      },
    }),
  ],
  session: {
    strategy: 'jwt',
    maxAge: 7 * 24 * 60 * 60, // 7 days
  },
  callbacks: {
    async jwt({ token, user, trigger, session }) {
      if (user) {
        token.id = user.id
        token.role = user.role
        token.plan = user.plan
        token.credits = user.credits
        token.oabNumber = user.oabNumber
        token.oabState = user.oabState
      }

      // Allow session updates (e.g., after plan change)
      if (trigger === 'update' && session) {
        token.plan = session.plan ?? token.plan
        token.credits = session.credits ?? token.credits
        token.role = session.role ?? token.role
      }

      return token
    },
    async session({ session, token }) {
      session.user.id = token.id
      session.user.role = token.role
      session.user.plan = token.plan
      session.user.credits = token.credits
      session.user.oabNumber = token.oabNumber
      session.user.oabState = token.oabState
      return session
    },
  },
  pages: {
    signIn: '/login',
    error: '/login',
  },
  secret: process.env.NEXTAUTH_SECRET,
}
