// app/api/auth/verify/route.ts
import { NextRequest, NextResponse } from 'next/server';
import jwt from 'jsonwebtoken';

export async function GET(req: NextRequest) {
  try {
    // Check API key
    const apiKey = req.headers.get("authorization");
    if (apiKey !== process.env.APP_API_KEY) {
      return NextResponse.json(
        { success: false, message: 'Unauthorized Access' },
        { status: 401 }
      );
    }
    
    // Get token from Authorization header
    const authHeader = req.headers.get('authorization');
    const token = authHeader?.split(' ')[1];
    
    if (!token) {
      return NextResponse.json(
        { success: false, message: 'No token provided' },
        { status: 401 }
      );
    }
    
    // Verify token
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET as string);
      return NextResponse.json({
        success: true,
        valid: true,
        user: decoded
      });
    } catch (error) {
      return NextResponse.json(
        { success: false, message: 'Invalid token' },
        { status: 401 }
      );
    }
  } catch (err: any) {
    console.error('Verify token error:', err);
    return NextResponse.json(
      { success: false, message: 'Internal server error' },
      { status: 500 }
    );
  }
}