import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export const dynamic = 'force-dynamic';

export async function POST(request: NextRequest) {
  try {
    const { token } = await request.json();
    
    if (!token) {
      return NextResponse.json({ valid: false }, { status: 401 });
    }
    
    // Check database for token
    const accessToken = await prisma.tesAccessToken.findUnique({
      where: { token }
    });
    
    if (!accessToken || !accessToken.isActive) {
      return NextResponse.json({ valid: false }, { status: 401 });
    }
    
    // Update last used
    await prisma.tesAccessToken.update({
      where: { id: accessToken.id },
      data: { lastUsed: new Date() }
    });
    
    // Parse permissions
    const permissions = JSON.parse(accessToken.permissions);
    
    return NextResponse.json({ 
      valid: true,
      userId: accessToken.userId,
      name: accessToken.name,
      permissions
    });
  } catch (error) {
    console.error('Auth error:', error);
    return NextResponse.json({ valid: false, error: 'Invalid request' }, { status: 400 });
  }
}
