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

const router = Router();

const toReport = (r: Record<string, unknown>) => ({
  id:         r.id,
  customerId: r.customer_id,
  machineId:  r.machine_id,
  category:   r.category,
  detail:     (r.detail as string) ?? '',
  createdAt:  r.created_at,
  status:     r.status,
  ...(r.admin_note && { adminNote: r.admin_note }),
});

// GET /api/reports
router.get('/', async (_req, res) => {
  try {
    const r = await pool.query('SELECT * FROM simo_reports ORDER BY created_at DESC');
    res.json(r.rows.map(toReport));
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// GET /api/reports/customer/:customerId
router.get('/customer/:customerId', async (req, res) => {
  try {
    const r = await pool.query(
      'SELECT * FROM simo_reports WHERE customer_id=$1 ORDER BY created_at DESC',
      [req.params.customerId],
    );
    res.json(r.rows.map(toReport));
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// POST /api/reports
router.post('/', async (req, res) => {
  const { customerId, machineId, category, detail } = req.body;
  try {
    const r = await pool.query(
      `INSERT INTO simo_reports (customer_id,machine_id,category,detail)
       VALUES ($1,$2,$3,$4) RETURNING *`,
      [customerId, machineId, category, detail ?? null],
    );
    res.status(201).json(toReport(r.rows[0]));
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// PUT /api/reports/:id
router.put('/:id', async (req, res) => {
  const { status, adminNote } = req.body;
  try {
    await pool.query(
      `UPDATE simo_reports SET status=$1,admin_note=$2 WHERE id=$3`,
      [status, adminNote ?? null, req.params.id],
    );
    res.json({ ok: true });
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// DELETE /api/reports/:id
router.delete('/:id', async (req, res) => {
  try {
    await pool.query('DELETE FROM simo_reports WHERE id=$1', [req.params.id]);
    res.json({ ok: true });
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

export default router;
