import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import fs from 'fs';
import path from 'path';

// Path to legacy JSON file-based subscriptions (kept for backward compat)
const HIJACK_SUBS_FILE = process.env.HIJACK_SUBS_FILE || '/opt/peercortex-app/data/hijack-subs.json';

interface HijackSubscribeBody {
  asn?: string | number;
  email?: string;
}

function loadHijackSubs(): any[] {
  try {
    if (!fs.existsSync(HIJACK_SUBS_FILE)) return [];
    return JSON.parse(fs.readFileSync(HIJACK_SUBS_FILE, 'utf8'));
  } catch {
    return [];
  }
}

export async function hijackSubscribeRoutes(fastify: FastifyInstance): Promise<void> {
  // OPTIONS preflight
  fastify.options('/hijack-subscribe', async (_request: FastifyRequest, reply: FastifyReply) => {
    reply.header('Access-Control-Allow-Origin', '*');
    reply.header('Access-Control-Allow-Methods', 'POST,OPTIONS');
    reply.header('Access-Control-Allow-Headers', 'Content-Type');
    return reply.status(204).send();
  });

  // POST /api/hijack-subscribe
  fastify.post<{ Body: HijackSubscribeBody }>(
    '/hijack-subscribe',
    async (request: FastifyRequest<{ Body: HijackSubscribeBody }>, reply: FastifyReply) => {
      reply.header('Access-Control-Allow-Origin', '*');

      try {
        const body = request.body as HijackSubscribeBody;
        const asnNum = String(body.asn || '').replace(/[^0-9]/g, '');

        if (!asnNum) {
          return reply.status(400).send({ error: 'asn required' });
        }

        const subs = loadHijackSubs();
        const exists = subs.find((s: any) => s.asn === asnNum);

        if (!exists) {
          // Add subscription without live hijack check (avoids circular dependency)
          // The scheduler will pick it up on next cycle
          subs.push({
            asn: asnNum,
            email: body.email || '',
            prefixes: [],
            subscribed: new Date().toISOString()
          });
          fs.mkdirSync(path.dirname(HIJACK_SUBS_FILE), { recursive: true });
          fs.writeFileSync(HIJACK_SUBS_FILE, JSON.stringify(subs, null, 2));
        }

        const entry = exists || subs[subs.length - 1];
        return reply.status(200).send({
          ok: true,
          asn: asnNum,
          monitoring: true,
          prefix_count: entry.prefixes?.length ?? 0
        });
      } catch (e: any) {
        return reply.status(500).send({ error: e.message });
      }
    }
  );
}
