const express = require('express');
const router = express.Router();
const License = require('../models/License');

// EA MT5 akan hit endpoint ini via POST
router.post('/validate', async (req, res) => {
   try {
       const { license_key, account_number, broker_name, broker_server } = req.body;

       if (!license_key || !account_number || !broker_name || !broker_server) {
           return res.json({ success: false, message: 'Parameter tidak lengkap (Butuh License, Account, Broker, Server)' });
       }

       const license = await License.findOne({ where: { license_key } });

       if (!license) {
           return res.json({ success: false, message: 'Lisensi tidak ditemukan' });
       }
       
       if (license.account_number !== account_number) {
           return res.json({ success: false, message: 'Lisensi tidak valid untuk Nomor Akun ini' });
       }

       if (license.broker_name !== broker_name) {
           return res.json({ success: false, message: 'Lisensi tidak valid untuk Broker ini' });
       }

       if (license.broker_server !== broker_server) {
           return res.json({ success: false, message: 'Lisensi tidak valid untuk Server Broker ini' });
       }

       if (license.status !== 'Active') {
           return res.json({ success: false, message: `Lisensi Anda: ${license.status}` });
       }

       if (license.expired_at && new Date() > new Date(license.expired_at)) {
           // Otomatis update status ke expired
           await license.update({ status: 'Expired' });
           return res.json({ success: false, message: 'Lisensi telah expired' });
       }

       // Validasi Sukses
       res.json({ success: true, message: 'Lisensi Valid' });

   } catch(error) {
       res.json({ success: false, message: 'Server error' });
   }
});


router.post('/register', async (req, res) => {
   try {
       const { account_number, broker_name, broker_server } = req.body;
       if (!account_number || !broker_name || !broker_server) {
           return res.json({ success: false, message: 'Data registrasi tidak lengkap' });
       }
       const existing = await License.findOne({ where: { account_number } });
       if (existing) {
           return res.json({ success: false, message: 'Akun sudah terdaftar!', license_key: existing.license_key });
       }
       const crypto = require('crypto');
       const license_key = 'TRIAL-' + crypto.randomBytes(4).toString('hex').toUpperCase();
       
       const expired_at = new Date();
       expired_at.setDate(expired_at.getDate() + 7);
       
       await License.create({
           license_key,
           account_number,
           broker_name,
           broker_server,
           status: 'Active',
           expired_at
       });
       
       res.json({ success: true, message: 'Trial 7 Hari Aktif', license_key });
   } catch(error) {
       res.json({ success: false, message: 'Server error registrasi' });
   }
});

module.exports = router;

