import { NextRequest, NextResponse } from 'next/server';
import { verifyToken } from './auth';

/**
 * Middleware to protect admin API routes
 * Returns 401 if not authenticated
 */
export function withAdminAuth(
  handler: (request: NextRequest) => Promise<NextResponse>
) {
  return async (request: NextRequest) => {
    // Get token from cookie
    const token = request.cookies.get('admin-token')?.value;

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

    // Verify token
    const payload = verifyToken(token);

    if (!payload || !payload.isAdmin) {
      return NextResponse.json(
        { error: 'Unauthorized - Invalid token' },
        { status: 401 }
      );
    }

    // Token is valid, proceed with the request
    return handler(request);
  };
}

/**
 * Check if request is from authenticated admin
 * For use in server components and API routes
 */
export function getAdminFromRequest(request: NextRequest) {
  const token = request.cookies.get('admin-token')?.value;

  if (!token) {
    return null;
  }

  const payload = verifyToken(token);

  if (!payload || !payload.isAdmin) {
    return null;
  }

  return {
    username: payload.username,
    isAdmin: true,
  };
}
