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

export const dynamic = 'force-dynamic';

// Verify token for write operations
function verifyToken(request: NextRequest): boolean {
  const authHeader = request.headers.get('authorization');
  const token = authHeader?.replace('Bearer ', '');
  return token === process.env.TES_ACCESS_TOKEN;
}

// GET - Read memories (optionally filtered by category)
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const category = searchParams.get('category');
    
    const where = category ? { category } : {};
    
    const memories = await prisma.tesMemory.findMany({
      where,
      orderBy: { priority: 'desc' }
    });
    
    return NextResponse.json({ memories });
  } catch (error) {
    console.error('Memory read error:', error);
    return NextResponse.json({ error: 'Failed to read memories' }, { status: 500 });
  }
}

// POST - Add or update a memory
export async function POST(request: NextRequest) {
  try {
    if (!verifyToken(request)) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    
    const { category, key, content, priority } = await request.json();
    
    if (!category || !key || !content) {
      return NextResponse.json({ error: 'category, key, and content are required' }, { status: 400 });
    }
    
    const memory = await prisma.tesMemory.upsert({
      where: { category_key: { category, key } },
      update: { content, priority: priority || 5 },
      create: { category, key, content, priority: priority || 5 }
    });
    
    return NextResponse.json({ success: true, memory });
  } catch (error) {
    console.error('Memory write error:', error);
    return NextResponse.json({ error: 'Failed to write memory' }, { status: 500 });
  }
}

// DELETE - Remove a memory
export async function DELETE(request: NextRequest) {
  try {
    if (!verifyToken(request)) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    
    const { searchParams } = new URL(request.url);
    const category = searchParams.get('category');
    const key = searchParams.get('key');
    
    if (!category || !key) {
      return NextResponse.json({ error: 'category and key are required' }, { status: 400 });
    }
    
    await prisma.tesMemory.delete({
      where: { category_key: { category, key } }
    });
    
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Memory delete error:', error);
    return NextResponse.json({ error: 'Failed to delete memory' }, { status: 500 });
  }
}
