import express from 'express';
import {
  listSessions,
  getSession,
  deleteSession,
  updateSessionTitle,
  getSessionMessages,
  convertToChatMessage,
  isClientReady,
} from '../services/aiService.js';

const router = express.Router();

router.use((req, res, next) => {
  if (!isClientReady()) {
    return res.status(503).json({ error: 'AI client not ready, please wait...' });
  }
  next();
});

/**
 * 获取会话列表
 */
router.get('/', async (req, res) => {
  try {
    const sessions = await listSessions();
    const sessionList = sessions.map((s) => ({
      id: s.id,
      name: s.title,
      createdAt: new Date(s.time.created * 1000).toISOString(),
      updatedAt: new Date(s.time.updated * 1000).toISOString(),
    }));
    res.json(sessionList);
  } catch (error) {
    console.error('[Sessions] List error:', error.message);
    res.status(500).json({ error: 'Failed to list sessions' });
  }
});

/**
 * 获取指定会话详情
 */
router.get('/:sessionId', async (req, res) => {
  try {
    const session = await getSession(req.params.sessionId);
    const messagesResult = await getSessionMessages(req.params.sessionId);
    const messages = (messagesResult || []).map((m) =>
      convertToChatMessage(m.info, m.parts)
    );

    res.json({
      id: session.id,
      name: session.title,
      messages,
      createdAt: new Date(session.time.created * 1000).toISOString(),
      updatedAt: new Date(session.time.updated * 1000).toISOString(),
    });
  } catch (error) {
    console.error('[Sessions] Get error:', error.message);
    if (error.message.includes('404')) {
      return res.status(404).json({ error: 'Session not found' });
    }
    res.status(500).json({ error: 'Failed to get session' });
  }
});

/**
 * 删除会话
 */
router.delete('/:sessionId', async (req, res) => {
  try {
    await deleteSession(req.params.sessionId);
    res.json({ success: true });
  } catch (error) {
    console.error('[Sessions] Delete error:', error.message);
    if (error.message.includes('404')) {
      return res.status(404).json({ error: 'Session not found' });
    }
    res.status(500).json({ error: 'Failed to delete session' });
  }
});

/**
 * 重命名会话
 */
router.put('/:sessionId/rename', async (req, res) => {
  const { name } = req.body;
  if (!name) {
    return res.status(400).json({ error: 'Name is required' });
  }
  try {
    await updateSessionTitle(req.params.sessionId, name);
    res.json({ success: true });
  } catch (error) {
    console.error('[Sessions] Rename error:', error.message);
    if (error.message.includes('404')) {
      return res.status(404).json({ error: 'Session not found' });
    }
    res.status(500).json({ error: 'Failed to rename session' });
  }
});

export { router as sessionsRouter };
