import { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { usersService } from '@/services/users';

// Détecter si on est en HTTPS
const isHttps = process.env.NEXTAUTH_URL?.startsWith('https://') ?? false;

export const authOptions: NextAuthOptions = {
  secret: process.env.NEXTAUTH_SECRET,
  useSecureCookies: isHttps,
  cookies: {
    sessionToken: {
      name: `${isHttps ? '__Secure-' : ''}next-auth.session-token`,
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        secure: isHttps,
      },
    },
  },
  providers: [
    CredentialsProvider({
      name: 'credentials',
      credentials: {
        email: { label: 'Email', type: 'email' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          console.error('[Auth] Missing credentials');
          return null;
        }

        try {
          console.log(`[Auth] Attempting login for: ${credentials.email}`);
          console.log(`[Auth] NEXTAUTH_URL: ${process.env.NEXTAUTH_URL}`);
          console.log(`[Auth] HTTPS mode: ${isHttps}`);

          // Chercher l'utilisateur dans la base de données
          const user = await usersService.getUserByEmail(credentials.email);

          if (!user) {
            console.error(`[Auth] User not found: ${credentials.email}`);
            return null;
          }

          console.log(`[Auth] User found: ${user.id} (${user.email})`);

          // Vérifier le mot de passe
          const isValidPassword = await usersService.verifyPassword(
            credentials.password,
            user.password
          );

          if (!isValidPassword) {
            console.error(`[Auth] Invalid password for: ${credentials.email}`);
            return null;
          }

          console.log(`[Auth] Login successful for: ${credentials.email}`);

          return {
            id: user.id,
            email: user.email,
            name:
              user.name ||
              `${user.firstName || ''} ${user.lastName || ''}`.trim() ||
              user.email,
            firstName: user.firstName || undefined,
            lastName: user.lastName || undefined,
            avatar: user.avatar || undefined,
            role: user.role,
          };
        } catch (error) {
          console.error('Auth error:', error);
          return null;
        }
      },
    }),
  ],
  pages: {
    signIn: '/login',
  },
  session: {
    strategy: 'jwt',
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id;
        token.firstName = user.firstName;
        token.lastName = user.lastName;
        token.avatar = user.avatar;
        token.role = user.role;
      }
      return token;
    },
    async session({ session, token }) {
      if (token && session.user) {
        session.user.id = token.id as string;
        session.user.firstName = token.firstName as string | undefined;
        session.user.lastName = token.lastName as string | undefined;
        session.user.avatar = token.avatar as string | undefined;
        session.user.role = token.role as string;
      }
      return session;
    },
  },
};
