import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import jwt from 'jsonwebtoken'

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key'

// Paths that require admin authentication
const protectedPaths = [
  '/admin/dashboard',
  '/admin/requests',
  '/admin/services',
  '/admin/users',
  '/admin/settings',
  '/admin/permissions',
  '/admin/templates',
  '/admin/contacts',
  '/admin/help'
]

// Public paths that don't require authentication
const publicPaths = [
  '/admin/login',
  '/api/admin/login',
  '/api/health',
  '/api/upload',
  '/api/seo',
  '/api/settings',
  '/api/service-requests',
  '/api/tracking',
  '/api/public'
]

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl

  // Check if the path is a protected admin path
  const isProtectedPath = protectedPaths.some(path => pathname.startsWith(path))
  const isPublicPath = publicPaths.some(path => pathname.startsWith(path))

  // If it's a protected path, check authentication
  if (isProtectedPath && !isPublicPath) {
    // Get token from Authorization header for API routes
    if (pathname.startsWith('/api/')) {
      const authHeader = request.headers.get('authorization')
      if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return NextResponse.json(
          { message: 'Unauthorized - No token provided' },
          { status: 401 }
        )
      }

      const token = authHeader.substring(7)
      try {
        jwt.verify(token, JWT_SECRET)
      } catch (error) {
        return NextResponse.json(
          { message: 'Unauthorized - Invalid token' },
          { status: 401 }
        )
      }
    } else {
      // For page routes, check localStorage token (client-side)
      // This is handled by the client-side auth check in components
      // We'll just add a header to help with debugging
      const response = NextResponse.next()
      response.headers.set('x-admin-auth-required', 'true')
      return response
    }
  }

  return NextResponse.next()
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * - public folder
     */
    '/((?!_next/static|_next/image|favicon.ico|public).*)',
  ],
}