import { WebSocket } from 'ws';
import { randomUUID } from 'crypto';
import { getDb } from '../db';

export function handleChat(ws: WebSocket) {
  let conversationId: string | null = null;

  ws.on('message', async (raw) => {
    try {
      const msg = JSON.parse(raw.toString());

      if (msg.type === 'init') {
        conversationId = msg.conversationId || randomUUID();
        const history = getDb().prepare(
          'SELECT * FROM messages WHERE conversation_id = ? ORDER BY created_at'
        ).all(conversationId);
        ws.send(JSON.stringify({ type: 'history', data: { conversationId, messages: history } }));
        return;
      }

      if (msg.type === 'chat') {
        const { content } = msg;
        const msgId = randomUUID();

        getDb().prepare(
          'INSERT INTO messages (id, conversation_id, role, content) VALUES (?, ?, ?, ?)'
        ).run(msgId, conversationId, 'user', content);

        ws.send(JSON.stringify({ type: 'message', data: { id: msgId, role: 'user', content } }));

        // Assistant echo (placeholder until LLM integration in Task 3.3)
        const assistantId = randomUUID();
        const assistantContent = `收到你的消息：「${content}」。Agent 引擎正在启动中...`;

        getDb().prepare(
          'INSERT INTO messages (id, conversation_id, role, content) VALUES (?, ?, ?, ?)'
        ).run(assistantId, conversationId, 'assistant', assistantContent);

        ws.send(JSON.stringify({
          type: 'message',
          data: { id: assistantId, role: 'assistant', content: assistantContent },
        }));
      }

      if (msg.type === 'create_conversation') {
        const { title, accountId } = msg;
        conversationId = randomUUID();
        getDb().prepare(
          'INSERT INTO conversations (id, title, account_id) VALUES (?, ?, ?)'
        ).run(conversationId, title || '新对话', accountId || null);
        ws.send(JSON.stringify({ type: 'conversation_created', data: { id: conversationId, title } }));
      }
    } catch (e) {
      ws.send(JSON.stringify({ type: 'error', data: { message: (e as Error).message } }));
    }
  });

  ws.on('close', () => {
    // cleanup if needed
  });
}
