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

export const dynamic = 'force-dynamic';

async function verifyPermission(request: NextRequest, permission: string): Promise<{ valid: boolean; userId?: string }> {
  const authHeader = request.headers.get('authorization');
  const token = authHeader?.replace('Bearer ', '');
  
  if (!token) return { valid: false };
  
  const accessToken = await prisma.tesAccessToken.findUnique({
    where: { token }
  });
  
  if (!accessToken || !accessToken.isActive) return { valid: false };
  
  const permissions = JSON.parse(accessToken.permissions);
  if (!permissions.includes(permission) && !permissions.includes('admin')) {
    return { valid: false };
  }
  
  return { valid: true, userId: accessToken.userId };
}

// GET - Get activity log
export async function GET(request: NextRequest) {
  try {
    const auth = await verifyPermission(request, 'activity');
    if (!auth.valid) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    
    const { searchParams } = new URL(request.url);
    const date = searchParams.get('date');
    const type = searchParams.get('type');
    const limit = parseInt(searchParams.get('limit') || '50');
    
    const where: any = {};
    
    if (date) {
      const targetDate = new Date(date);
      const startOfDay = new Date(targetDate.setHours(0, 0, 0, 0));
      const endOfDay = new Date(targetDate.setHours(23, 59, 59, 999));
      where.timestamp = { gte: startOfDay, lte: endOfDay };
    }
    
    if (type) {
      where.type = type;
    }
    
    const activities = await prisma.tesActivity.findMany({
      where,
      orderBy: { timestamp: 'desc' },
      take: limit
    });
    
    return NextResponse.json({ activities });
  } catch (error) {
    console.error('Activity read error:', error);
    return NextResponse.json({ error: 'Failed to read activities' }, { status: 500 });
  }
}

// POST - Log an activity
export async function POST(request: NextRequest) {
  try {
    // Activity logging can be internal - check for API key or token
    const authHeader = request.headers.get('authorization');
    const token = authHeader?.replace('Bearer ', '');
    
    // Allow internal calls with API key
    if (token !== process.env.TES_ACCESS_TOKEN && token !== process.env.ABACUSAI_API_KEY) {
      const auth = await verifyPermission(request, 'admin');
      if (!auth.valid) {
        return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
      }
    }
    
    const { type, description, metadata } = await request.json();
    
    if (!type || !description) {
      return NextResponse.json({ error: 'type and description required' }, { status: 400 });
    }
    
    const activity = await prisma.tesActivity.create({
      data: {
        type,
        description,
        metadata: metadata ? JSON.stringify(metadata) : null
      }
    });
    
    return NextResponse.json({ success: true, activity });
  } catch (error) {
    console.error('Activity log error:', error);
    return NextResponse.json({ error: 'Failed to log activity' }, { status: 500 });
  }
}
