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

// POST - Save chat history
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { user_id, agent_id, session_id, title, messages } = body;
    const db = getDatabase();

    // Validate required fields
    if (!user_id || !agent_id || !session_id) {
      return NextResponse.json(
        { error: 'Missing required fields: user_id, agent_id, session_id' },
        { status: 400 }
      );
    }

    // Check if session already exists
    const existingSession = db.prepare(
      'SELECT id FROM chat_sessions WHERE session_id = ?'
    ).get(session_id);

    if (existingSession) {
      // Update existing session
      db.prepare(`
        UPDATE chat_sessions 
        SET title = ?, updated_at = CURRENT_TIMESTAMP, message_count = ?
        WHERE session_id = ?
      `).run(title || 'Chat Session', messages?.length || 0, session_id);
    } else {
      // Create new session
      db.prepare(`
        INSERT INTO chat_sessions (session_id, user_id, agent_id, title, message_count)
        VALUES (?, ?, ?, ?, ?)
      `).run(session_id, user_id, agent_id, title || 'Chat Session', messages?.length || 0);
    }

    // Save messages if provided
    if (messages && Array.isArray(messages)) {
      // Delete existing messages for this session
      db.prepare('DELETE FROM chat_messages WHERE session_id = ?').run(session_id);

      // Insert new messages
      const insertMessage = db.prepare(`
        INSERT INTO chat_messages (session_id, message_type, content)
        VALUES (?, ?, ?)
      `);

      const insertMany = db.transaction((messages: any[]) => {
        for (const message of messages) {
          insertMessage.run(session_id, message.type, message.content);
        }
      });

      insertMany(messages);
    }

    return NextResponse.json(
      { 
        success: true, 
        message: 'Chat history saved successfully',
        session_id 
      },
      { status: 200 }
    );

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

// GET - Get chat history
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const user_id = searchParams.get('user_id');
    const agent_id = searchParams.get('agent_id');
    const session_id = searchParams.get('session_id');
    const db = getDatabase();

    // Validate required fields
    if (!user_id) {
      return NextResponse.json(
        { error: 'Missing required parameter: user_id' },
        { status: 400 }
      );
    }

    let sessions;
    let params: any[] = [user_id];

    // Get all sessions for user (simplified - only based on user_id)
    sessions = db.prepare(`
      SELECT *
      FROM chat_sessions
      WHERE user_id = ?
      ORDER BY id DESC
    `).all(user_id);

    return NextResponse.json({
      sessions,
      total: sessions.length
    });

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