const express = require('express');
const router = express.Router();
const License = require('../models/License');
const auth = require('../middleware/authMiddleware');
const crypto = require('crypto');

router.use(auth);

router.get('/', async (req, res) => {
   try {
       const licenses = await License.findAll({ order: [['createdAt', 'DESC']] });
       res.json(licenses);
   } catch(error) {
       res.status(500).json({ error: error.message });
   }
});

router.post('/', async (req, res) => {
   try {
       const { account_number, broker_name, broker_server, validity_days } = req.body;
       const license_key = 'KJFX-' + crypto.randomBytes(8).toString('hex').toUpperCase();

       let expired_at = null;
       if (validity_days) {
           expired_at = new Date();
           expired_at.setDate(expired_at.getDate() + parseInt(validity_days));
       }

       const license = await License.create({
           license_key, account_number, broker_name, broker_server, expired_at
       });
       res.json(license);
   } catch(error) {
       res.status(500).json({ error: error.message });
   }
});

router.put('/:id', async (req, res) => {
   try {
       const { status } = req.body;
       await License.update({ status }, { where: { id: req.params.id } });
       res.json({ message: 'Lisensi diupdate' });
   } catch(error) {
       res.status(500).json({ error: error.message });
   }
});

router.delete('/:id', async (req, res) => {
   try {
       await License.destroy({ where: { id: req.params.id } });
       res.json({ message: 'Lisensi dihapus' });
   } catch(error) {
       res.status(500).json({ error: error.message });
   }
});

module.exports = router;
