// routes/redirects.js
const express = require('express');
const router  = express.Router();
const fs      = require('fs');
const path    = require('path');

const DATA_FILE = path.join(__dirname, '..', 'data', 'redirects.json');

// Ensure data directory exists
const dataDir = path.dirname(DATA_FILE);
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });

// Load redirects from file
function loadRedirects() {
  try {
    if (!fs.existsSync(DATA_FILE)) return [];
    return JSON.parse(fs.readFileSync(DATA_FILE, 'utf8'));
  } catch(e) {
    return [];
  }
}

// Save redirects to file
function saveRedirects(redirects) {
  fs.writeFileSync(DATA_FILE, JSON.stringify(redirects, null, 2));
}

// Generate unique ID
function genId() {
  return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
}

// ── List all redirects ────────────────────────────────────
router.get('/', (req, res) => {
  try {
    res.json({ ok: true, redirects: loadRedirects() });
  } catch(e) {
    res.json({ ok: false, error: e.message });
  }
});

// ── Create redirect ───────────────────────────────────────
router.post('/', (req, res) => {
  try {
    const { source, destination, type, active, note } = req.body;
    if (!source || !destination) return res.json({ ok: false, error: 'Source and destination are required' });
    if (!source.startsWith('/')) return res.json({ ok: false, error: 'Source must start with /' });

    const redirects = loadRedirects();

    // Check for duplicate source
    const exists = redirects.find(function(r) { return r.source === source; });
    if (exists) return res.json({ ok: false, error: 'A redirect for "' + source + '" already exists' });

    const redirect = {
      id         : genId(),
      source     : source.trim(),
      destination: destination.trim(),
      type       : type === '302' ? 302 : 301,
      active     : active !== false,
      note       : note || '',
      createdAt  : new Date().toISOString(),
      hits       : 0
    };

    redirects.push(redirect);
    saveRedirects(redirects);
    res.json({ ok: true, redirect });
  } catch(e) {
    res.json({ ok: false, error: e.message });
  }
});

// ── Update redirect ───────────────────────────────────────
router.put('/:id', (req, res) => {
  try {
    const { source, destination, type, active, note } = req.body;
    const redirects = loadRedirects();
    const idx = redirects.findIndex(function(r) { return r.id === req.params.id; });
    if (idx === -1) return res.json({ ok: false, error: 'Redirect not found' });

    // Check for duplicate source (excluding current)
    const duplicate = redirects.find(function(r) { return r.source === source && r.id !== req.params.id; });
    if (duplicate) return res.json({ ok: false, error: 'Another redirect for "' + source + '" already exists' });

    redirects[idx] = Object.assign(redirects[idx], {
      source     : source ? source.trim() : redirects[idx].source,
      destination: destination ? destination.trim() : redirects[idx].destination,
      type       : type ? (type === '302' ? 302 : 301) : redirects[idx].type,
      active     : active !== undefined ? active : redirects[idx].active,
      note       : note !== undefined ? note : redirects[idx].note,
      updatedAt  : new Date().toISOString()
    });

    saveRedirects(redirects);
    res.json({ ok: true, redirect: redirects[idx] });
  } catch(e) {
    res.json({ ok: false, error: e.message });
  }
});

// ── Toggle active ─────────────────────────────────────────
router.post('/:id/toggle', (req, res) => {
  try {
    const redirects = loadRedirects();
    const r = redirects.find(function(r) { return r.id === req.params.id; });
    if (!r) return res.json({ ok: false, error: 'Redirect not found' });
    r.active = !r.active;
    saveRedirects(redirects);
    res.json({ ok: true, active: r.active });
  } catch(e) {
    res.json({ ok: false, error: e.message });
  }
});

// ── Delete redirect ───────────────────────────────────────
router.delete('/:id', (req, res) => {
  try {
    const redirects = loadRedirects();
    const filtered = redirects.filter(function(r) { return r.id !== req.params.id; });
    if (filtered.length === redirects.length) return res.json({ ok: false, error: 'Redirect not found' });
    saveRedirects(filtered);
    res.json({ ok: true });
  } catch(e) {
    res.json({ ok: false, error: e.message });
  }
});

// ── Test redirect ─────────────────────────────────────────
router.get('/test', (req, res) => {
  try {
    const { source } = req.query;
    const redirects = loadRedirects();
    const match = redirects.find(function(r) { return r.source === source && r.active; });
    if (!match) return res.json({ ok: true, found: false, message: 'No active redirect found for "' + source + '"' });
    res.json({ ok: true, found: true, redirect: match });
  } catch(e) {
    res.json({ ok: false, error: e.message });
  }
});

// ── Export middleware for server.js ──────────────────────
// Add this to server.js BEFORE your routes:
// 
// const { redirectMiddleware } = require('./routes/redirects');
// app.use(redirectMiddleware);
//
router.redirectMiddleware = function(req, res, next) {
  try {
    const redirects = loadRedirects();
    const match = redirects.find(function(r) { return r.source === req.path && r.active; });
    if (!match) return next();
    match.hits = (match.hits || 0) + 1;
    saveRedirects(redirects);
    res.redirect(match.type, match.destination);
  } catch(e) {
    next();
  }
};

module.exports = router;