'use strict';
const express = require('express');
const { db } = require('../db');
const { verifyPayfastSignature } = require('../lib/payments');

const router = express.Router();

router.post('/notify', (req, res) => {
  const body = req.body || {};
  const order = db.prepare('SELECT * FROM orders WHERE order_number = ?').get(body.m_payment_id);
  if (!order) {
    console.log('[payfast] notify for unknown order', body.m_payment_id);
    return res.send('OK');
  }
  if (!verifyPayfastSignature(body)) {
    console.log('[payfast] signature mismatch for', order.order_number);
    return res.send('INVALID SIGNATURE');
  }
  const paid = body.payment_status === 'COMPLETE';
  if (paid) {
    db.prepare(
      "UPDATE orders SET status='confirmed', payment_status='paid', payment_method='payfast' WHERE id = ?"
    ).run(order.id);
    console.log('[payfast] order marked paid:', order.order_number);
  }
  res.send('OK');
});

router.get('/notify', (req, res) => res.send('OK'));

module.exports = { notifyRouter: router };
