const express = require("express");
const router = express.Router();
const Customer = require('../models/Customer');
const crypto = require('crypto');


const { forwardAuthenticated, ensureAuthenticated } = require('../config/auth');


// GET Add Customer (with search)
router.get("/add-customer", ensureAuthenticated, async (req, res) => {
  try {
    const search = req.query.search || "";
    let query = {};

    if (search) {
      query = {
        $or: [
          { name: { $regex: search, $options: "i" } },
          { email: { $regex: search, $options: "i" } },
          { phone: { $regex: search, $options: "i" } },
          { fullLicenseKey: { $regex: search, $options: "i" } }
        ]
      };
    }

    const customers = await Customer.find(query).sort({ createdAt: -1 });

    res.render("add-customer", {
      customers,
      search
    });
  } catch (err) {
    console.error(err);
    req.flash("error_msg", "Error fetching customers");
    res.redirect("/admin-dashboard");
  }
});



router.post("/add-customer", async (req, res) => {
  try {
    const customer = new Customer({
      name: req.body.name,
      email: req.body.email,
      phone: req.body.phone,
      fullLicenseKey: req.body.fullLicenseKey,
      price: req.body.price,
      renewal: req.body.renewal,
    });

    await customer.save();
    req.flash('success_msg', 'Customer Added Successfully.');
    res.redirect('/admin/add-customer');

  } catch (err) {
    console.error(err);
    req.flash('error_msg', 'Unable to add Customer. Please try again.');
    res.redirect('/add-customer');
  }
});





// Update customer
router.post('/update/:id', async (req, res) => {
  const id = req.params.id;

  // Build update object
  const update = {
    name: req.body.name,
    email: req.body.email,
    phone: req.body.phone,
    fullLicenseKey: req.body.fullLicenseKey,
    price: req.body.price,
    renewal: req.body.renewal,
  };

  console.log("Updating customer ID:", id);
  console.log("Form data:", update);

  try {
    const updatedCustomer = await Customer.findByIdAndUpdate(id, update, {
      new: true,
      runValidators: true, // ensure schema validation
    });

    if (!updatedCustomer) {
      req.flash('error_msg', 'Customer not found.');
      return res.redirect('/admin/add-customer');
    }

    req.flash('success_msg', 'Customer Updated Successfully.');
    res.redirect('/admin/add-customer');
  } catch (err) {
    console.error(err);
    req.flash('error_msg', 'Unable to update Customer.');
    res.redirect('/admin/add-customer');
  }
});

// Delete customer
router.post('/delete/:id', async (req, res) => {
  const id = req.params.id;

  try {
    const deletedCustomer = await Customer.findByIdAndDelete(id);

    if (!deletedCustomer) {
      req.flash('error_msg', 'Customer not found.');
      return res.redirect('/admin/add-customer');
    }

    req.flash('success_msg', 'Customer deleted successfully.');
    res.redirect('/admin/add-customer');
  } catch (err) {
    console.error(err);
    req.flash('error_msg', 'Unable to delete customer.');
    res.redirect('/admin/add-customer');
  }
});


// Route: generate a secure license key
router.get('/generate-license', async (req, res) => {
  try {
    // Generate 16 bytes = 32 hex characters
    const raw = crypto.randomBytes(16).toString('hex').toUpperCase();

    // Format key as XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX
    const formattedKey = raw.match(/.{1,4}/g).join('-');

    // Optionally store in DB as reserved key (depends on your schema)
    // Example: create a placeholder customer with only license key
    // const customer = await Customer.create({ fullLicenseKey: formattedKey });
    
    // If you want, you can just return key without DB entry yet
    res.json({ key: formattedKey });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Unable to generate key' });
  }
});


module.exports = router;
