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

const router = Router();

const toTx = (r: Record<string, unknown>) => ({
  id:            r.id,
  customerId:    r.customer_id,
  machineId:     r.machine_id,
  amount:        Number(r.amount),
  paymentMethod: r.payment_method,
  date:          r.date as string,
  ...(r.note && { note: r.note }),
});

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

// GET /api/transactions/customer/:customerId
// ดึงจาก amount_payment โดย join กับ simo_machines ผ่าน serial_no
// แต่ละ row ที่มีทั้ง cash+digital จะถูก split เป็น 2 records
router.get('/customer/:customerId', async (req, res) => {
  try {
    const r = await pool.query(
      `SELECT
         ap.id::text || '_cash'    AS id,
         m.customer_id,
         m.id                      AS machine_id,
         ap.coin                   AS amount,
         'cash'                    AS payment_method,
         ap.time1                  AS date
       FROM amount_payment ap
       JOIN simo_machines m ON m.serial_number = ap.serial_no
       WHERE m.customer_id = $1
         AND ap.time1 >= m.purchase_date
         AND ap.coin > 0

       UNION ALL

       SELECT
         ap.id::text || '_digital' AS id,
         m.customer_id,
         m.id                      AS machine_id,
         (ap.pay_by_wechat + ap.pay_by_rabbit_line_pay + ap.pay_by_promptpay
          + ap.pay_by_truemoney + ap.pay_by_point) AS amount,
         'promptpay'               AS payment_method,
         ap.time1                  AS date
       FROM amount_payment ap
       JOIN simo_machines m ON m.serial_number = ap.serial_no
       WHERE m.customer_id = $1
         AND ap.time1 >= m.purchase_date
         AND (ap.pay_by_wechat + ap.pay_by_rabbit_line_pay + ap.pay_by_promptpay
              + ap.pay_by_truemoney + ap.pay_by_point) > 0

       ORDER BY date DESC, id DESC`,
      [req.params.customerId],
    );
    res.json(r.rows.map(toTx));
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// POST /api/transactions
router.post('/', async (req, res) => {
  const { customerId, machineId, amount, paymentMethod, date, note } = req.body;
  try {
    const r = await pool.query(
      `INSERT INTO simo_transactions (customer_id,machine_id,amount,payment_method,date,note)
       VALUES ($1,$2,$3,$4,$5,$6) RETURNING *`,
      [customerId, machineId, amount, paymentMethod, date, note ?? null],
    );
    res.status(201).json(toTx(r.rows[0]));
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

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

export default router;
