import { NextRequest, NextResponse } from 'next-auth/react';
import { UserRole } from '../config/auth.config';

/**
 * Middleware to protect routes that require authentication
 */
export function withAuth(
  request: NextRequest,
  options?: {
    signInPath?: string;
  }
): NextResponse {
  const token = request.cookies.get('next-auth.session-token')?.value;
  const signInPath = options?.signInPath ?? '/auth/signin';

  if (!token) {
    const signInUrl = new URL(signInPath, request.url);
    signInUrl.searchParams.set('callbackUrl', request.nextUrl.pathname);
    return NextResponse.redirect(signInUrl);
  }

  return NextResponse.next();
}

/**
 * Middleware to check if user has required role
 */
export function withRole(
  response: NextResponse,
  request: NextRequest,
  requiredRoles: UserRole[]
): NextResponse {
  const token = request.cookies.get('next-auth.session-token')?.value;

  if (!token) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  // TODO: Decode JWT and check role
  // For now, allow all authenticated users
  return response;
}

/**
 * Middleware to protect API routes
 */
export function protectApiRoute(request: NextRequest): NextResponse {
  const authHeader = request.headers.get('authorization');

  if (!authHeader?.startsWith('Bearer ')) {
    return NextResponse.json({ error: 'Missing or invalid token' }, { status: 401 });
  }

  const token = authHeader.split(' ')[1];

  try {
    // TODO: Verify JWT token
    return NextResponse.next();
  } catch (error) {
    return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
  }
}
