import { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';

export interface AuthUser {
  id: string;
  email: string;
  role: 'CLIENT' | 'FREELANCER' | 'ADMIN';
  name?: string;
}

export async function getAuthUser(request: NextRequest): Promise<AuthUser | null> {
  try {
    const token = await getToken({ 
      req: request, 
      secret: process.env.NEXTAUTH_SECRET 
    });
    
    console.log('🔐 Middleware token check:', {
      hasToken: !!token,
      tokenRole: token?.role,
      tokenId: token?.id,
      url: request.url
    });
    
    if (!token) {
      console.log('❌ No token found in middleware');
      return null;
    }

    return {
      id: token.id as string,
      email: token.email as string,
      name: token.name as string,
      role: token.role as 'CLIENT' | 'FREELANCER' | 'ADMIN',
    };
  } catch (error) {
    console.error('Error getting auth user:', error);
    return null;
  }
}

export function isProtectedClientRoute(pathname: string): boolean {
  return pathname.includes('/client/') || pathname.endsWith('/client');
}

export function isProtectedFreelancerRoute(pathname: string): boolean {
  return pathname.includes('/freelancer/') || pathname.endsWith('/freelancer');
}

export function isProtectedRoute(pathname: string): boolean {
  return isProtectedClientRoute(pathname) || isProtectedFreelancerRoute(pathname);
}

export function getRedirectUrl(userRole: string | undefined, locale: string): string {
  switch (userRole) {
    case 'CLIENT':
      return `/${locale}/client/my-projects`;
    case 'FREELANCER':
      return `/${locale}/freelancer/my-projects`;
    case 'ADMIN':
      return `/${locale}/admin/dashboard`;
    default:
      return `/${locale}/login`;
  }
}