import { NextRequest, NextResponse } from 'next/server';
import getDatabase from '@/lib/database';

interface ChatSession {
  id: string;
  session_id: string;
  user_id: string;
  agent_id: string;
  title: string;
  message_count: number;
  created_at: string;
  updated_at: string;
}

interface ChatMessage {
  id: string;
  session_id: string;
  message_type: string;
  content: string;
  created_at: string;
}

// GET - Get session details by id
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const db = getDatabase();

    if (!id) {
      return NextResponse.json({ error: 'ID is required' }, { status: 400 });
    }

    // Get session details by id
    const session = db.prepare(`
      SELECT * FROM chat_sessions 
      WHERE id = ?
    `).get(id) as ChatSession | undefined;

    if (!session) {
      return NextResponse.json({ error: 'Session not found' }, { status: 404 });
    }

    // Get messages for this session
    const messages = db.prepare(`
      SELECT * FROM chat_messages 
      WHERE session_id = ? 
      ORDER BY created_at ASC
    `).all(session.session_id) as ChatMessage[];

    return NextResponse.json({
      success: true,
      session,
      messages
    }, { status: 200 });

  } catch (error) {
    console.error('Error fetching session details:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

// DELETE - Delete a specific chat session
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const { searchParams } = new URL(request.url);
    const user_id = searchParams.get('user_id');
    const db = getDatabase();

    if (!id) {
      return NextResponse.json({ error: 'ID is required' }, { status: 400 });
    }

    if (!user_id) {
      return NextResponse.json({ error: 'User ID is required' }, { status: 400 });
    }

    // Check if session exists and belongs to user
    const session = db.prepare(`
      SELECT id FROM chat_sessions 
      WHERE id = ? AND user_id = ?
    `).get(id, user_id) as { id: string } | undefined;

    if (!session) {
      return NextResponse.json({ error: 'Session not found or access denied' }, { status: 404 });
    }

    // Delete session (messages will be deleted automatically due to CASCADE)
    db.prepare('DELETE FROM chat_sessions WHERE id = ?').run(id);

    return NextResponse.json({ 
      success: true, 
      message: 'Session deleted successfully' 
    }, { status: 200 });

  } catch (error) {
    console.error('Error deleting session:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
} 