import { Router, Request } from 'express';
import pool from '../db';

const router = Router();

// GET /api/conversations — paginated list
router.get('/', async (req: Request, res) => {
  try {
    const page = Math.max(1, parseInt(req.query.page as string) || 1);
    const limit = Math.min(100, parseInt(req.query.limit as string) || 25);
    const offset = (page - 1) * limit;
    const agent = req.query.agent as string;
    const contactId = req.query.contact as string;
    const chatType = req.query.type as string;

    const conditions: string[] = [];
    const params: any[] = [];
    let paramIdx = 1;

    if (agent) {
      conditions.push(`s.agent = $${paramIdx}`);
      params.push(agent);
      paramIdx++;
    }

    if (contactId) {
      conditions.push(`s.contact_id = $${paramIdx}`);
      params.push(contactId);
      paramIdx++;
    }

    if (chatType) {
      conditions.push(`s.chat_type = $${paramIdx}`);
      params.push(chatType);
      paramIdx++;
    }

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

    const [countResult, dataResult] = await Promise.all([
      pool.query(`SELECT COUNT(*) FROM crm_sessions s ${whereClause}`, params),
      pool.query(`
        SELECT s.*,
          c.display_name as contact_name, c.username as contact_username, c.telegram_id,
          (SELECT content FROM crm_messages m
           WHERE m.session_id = s.id AND m.content_type = 'text'
           ORDER BY m.timestamp DESC LIMIT 1) as last_message
        FROM crm_sessions s
        LEFT JOIN crm_contacts c ON s.contact_id = c.id
        ${whereClause}
        ORDER BY s.last_activity DESC
        LIMIT $${paramIdx} OFFSET $${paramIdx + 1}
      `, [...params, limit, offset]),
    ]);

    res.json({
      conversations: dataResult.rows.map(r => ({
        ...r,
        last_message: r.last_message?.slice(0, 200),
      })),
      total: parseInt(countResult.rows[0].count),
      page,
      limit,
      totalPages: Math.ceil(parseInt(countResult.rows[0].count) / limit),
    });
  } catch (err: any) {
    console.error('Conversations list error:', err);
    res.status(500).json({ error: err.message });
  }
});

// GET /api/conversations/:id — detail with messages
router.get('/:id', async (req: Request, res) => {
  try {
    const { id } = req.params;
    const page = Math.max(1, parseInt(req.query.page as string) || 1);
    const limit = Math.min(200, parseInt(req.query.limit as string) || 50);
    const offset = (page - 1) * limit;

    const [session, messages, messageCount] = await Promise.all([
      pool.query(`
        SELECT s.*,
          c.display_name as contact_name, c.username as contact_username, c.telegram_id
        FROM crm_sessions s
        LEFT JOIN crm_contacts c ON s.contact_id = c.id
        WHERE s.id = $1
      `, [id]),
      pool.query(`
        SELECT m.*, c.display_name as sender_name, c.telegram_id as sender_telegram_id
        FROM crm_messages m
        LEFT JOIN crm_contacts c ON m.contact_id = c.id
        WHERE m.session_id = $1
        ORDER BY m.timestamp ASC
        LIMIT $2 OFFSET $3
      `, [id, limit, offset]),
      pool.query('SELECT COUNT(*) FROM crm_messages WHERE session_id = $1', [id]),
    ]);

    if (session.rows.length === 0) {
      res.status(404).json({ error: 'Conversation not found' });
      return;
    }

    res.json({
      session: session.rows[0],
      messages: messages.rows,
      total: parseInt(messageCount.rows[0].count),
      page,
      limit,
      totalPages: Math.ceil(parseInt(messageCount.rows[0].count) / limit),
    });
  } catch (err: any) {
    console.error('Conversation detail error:', err);
    res.status(500).json({ error: err.message });
  }
});

export default router;
