import { Router } from 'express';
import { db } from '../db.js';
import { authMiddleware } from '../middleware/auth.js';

const router = Router();
router.use(authMiddleware);

router.get('/', (req, res) => {
  const rows = db.prepare(`
    SELECT id, subject, message, status, created_at FROM support_tickets
    WHERE user_id = ? ORDER BY created_at DESC
  `).all(req.user.id);
  res.json({
    tickets: rows.map((r) => ({
      id: r.id,
      subject: r.subject,
      message: r.message,
      status: r.status,
      createdAt: r.created_at,
    })),
  });
});

router.post('/', (req, res) => {
  const { subject, message } = req.body;
  if (!subject || !message) return res.status(400).json({ error: 'موضوع و پیام الزامی است' });
  const result = db.prepare(`
    INSERT INTO support_tickets (user_id, subject, message) VALUES (?, ?, ?)
  `).run(req.user.id, subject, message);
  res.status(201).json({ id: result.lastInsertRowid, message: 'تیکت ثبت شد' });
});

export default router;
