import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { getJWT, refreshJWT } from '@/app/actions/authAction';
import jwt_decode from 'jsonwebtoken';
import logger from '@/utils/logger';

const options = {
  secret: process.env.AUTH_SECRET,
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        email: { label: 'Email', type: 'email' },
        password: { label: 'Password', type: 'password' },
        role_type: { label: 'Role Type', type: 'text' }
      },
      authorize: async (credentials, req) => {
        try {
          const data = {
            email: credentials.email,
            password: credentials.password,
            role_type: credentials.role_type
          };

          const user = await getJWT(data);

          if (user) {
            return user;
          }
        } catch (error) {
          throw new Error(error.message || 'Invalid credentials');
        }
      }
    })
  ],
  session: {
    strategy: "jwt",
    maxAge: 30 * 24 * 60 * 60, // 30 jours
    updateAge: 24 * 60 * 60, // 24 heures
  },
  cookies: {
    sessionToken: {
      name: 'n3wtschool_session_token',
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        secure: process.env.NODE_ENV === 'production'
      }
    }
  },
  callbacks: {
    async jwt({ token, user }) {
      // Si c'est la première connexion
      if (user && user?.token) {
        return {
          ...token,
          token: user.token,
          refresh: user.refresh,
          tokenExpires: jwt_decode.decode(user.token).exp * 1000
        };
      }

      // Vérifier si le token n'est pas expiré
      if (Date.now() < token.tokenExpires) {
        return token;
      }

      // Token expiré, essayer de le rafraîchir
      try {
        const response = await refreshJWT({ refresh: token.refresh });
        if (response && response?.token) {
          return {
              ...token,
              token: response.token,
              refresh: response.refresh,
              tokenExpires: jwt_decode.decode(response.token).exp * 1000
            };
        }
        else{
          throw new Error('Failed to refresh token');
        }
      } catch (error) {
        logger.error("Refresh token failed:", error);
        return token;
      }
    },
    async session({ session, token }) {
      if (token && token?.token) {
        const { user_id, email, roles } = jwt_decode.decode(token.token);
        session.user = {
          ...session.user,
          token: token.token,
          refresh: token.refresh,
          user_id: user_id,
          email: email,
          roles: roles
        };
      }
      return session;
    }
  },
  pages: {
    signIn: '/[locale]/users/login'
  },
  csrf: true
};

export default (req, res) => NextAuth(req, res, options);