import { Router, Request, Response, NextFunction } from 'express';
import { query, queryOne } from '../db';

const router = Router();

// GET /api/lists
router.get('/', async (_req: Request, res: Response, next: NextFunction) => {
  try {
    const lists = await query(`
      SELECT l.*, COUNT(lc.contact_id)::int AS contact_count
      FROM lists l
      LEFT JOIN list_contacts lc ON lc.list_id = l.id
      GROUP BY l.id
      ORDER BY l.created_at DESC
    `);
    res.json(lists);
  } catch (err) { next(err); }
});

// GET /api/lists/:id
router.get('/:id', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const list = await queryOne('SELECT * FROM lists WHERE id=$1', [req.params.id]);
    if (!list) return res.status(404).json({ error: 'List not found' });
    res.json(list);
  } catch (err) { next(err); }
});

// GET /api/lists/:id/contacts
router.get('/:id/contacts', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const contacts = await query(`
      SELECT c.*, lc.subscribed_at
      FROM list_contacts lc
      JOIN contacts c ON c.id = lc.contact_id
      WHERE lc.list_id = $1
      ORDER BY lc.subscribed_at DESC
      LIMIT 500
    `, [req.params.id]);
    res.json(contacts);
  } catch (err) { next(err); }
});

// POST /api/lists
router.post('/', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { name, description } = req.body;
    const list = await queryOne(
      'INSERT INTO lists (name, description) VALUES ($1,$2) RETURNING *',
      [name, description || null]
    );
    res.status(201).json(list);
  } catch (err) { next(err); }
});

// PATCH /api/lists/:id
router.patch('/:id', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { name, description } = req.body;
    const list = await queryOne(
      'UPDATE lists SET name=$1, description=$2 WHERE id=$3 RETURNING *',
      [name, description || null, req.params.id]
    );
    if (!list) return res.status(404).json({ error: 'List not found' });
    res.json(list);
  } catch (err) { next(err); }
});

// DELETE /api/lists/:id
router.delete('/:id', async (req: Request, res: Response, next: NextFunction) => {
  try {
    await query('DELETE FROM lists WHERE id=$1', [req.params.id]);
    res.status(204).send();
  } catch (err) { next(err); }
});

// POST /api/lists/:id/contacts — add contacts to list
router.post('/:id/contacts', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { contact_ids } = req.body as { contact_ids: string[] };
    for (const cid of contact_ids) {
      await query(
        'INSERT INTO list_contacts (list_id, contact_id) VALUES ($1,$2) ON CONFLICT DO NOTHING',
        [req.params.id, cid]
      );
    }
    res.json({ message: `Added ${contact_ids.length} contact(s)` });
  } catch (err) { next(err); }
});

// DELETE /api/lists/:id/contacts/:contactId
router.delete('/:id/contacts/:contactId', async (req: Request, res: Response, next: NextFunction) => {
  try {
    await query('DELETE FROM list_contacts WHERE list_id=$1 AND contact_id=$2', [req.params.id, req.params.contactId]);
    res.status(204).send();
  } catch (err) { next(err); }
});

export default router;
