import { NextResponse } from 'next/server';
import { db, writerDb } from "@/drizzle/db";
import { systemFeatures, quantumLogs } from "@/drizzle/schema";
import { eq, inArray } from 'drizzle-orm';
import { cookies } from 'next/headers';
import jwt from 'jsonwebtoken';
import fs from 'fs';
import path from 'path';

export const dynamic = 'force-dynamic';

export async function GET(_req: Request) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('jumpa_token')?.value;

    if (!token) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as { role: string };
    if (decoded.role !== 'superadmin') return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

    // AUTO-SCANNER ENGINE
    const manifests = [
      { module: 'JC', path: path.join(process.cwd(), '../c/quantum.manifest.json') },
      { module: 'JVC', path: path.join(process.cwd(), '../vc/quantum.manifest.json') },
      { module: 'IAM', path: path.join(process.cwd(), 'quantum.manifest.json') }
    ];

    const currentFeatures = await db.select().from(systemFeatures);
    const existingKeys = new Set(currentFeatures.map(f => f.key));

    for (const m of manifests) {
      try {
        if (fs.existsSync(m.path)) {
          const content = fs.readFileSync(m.path, 'utf8');
          const features = JSON.parse(content);
          
          // FASE 12: Auto-Migration Legacy Features from JC to JVC
          if (m.module === 'JVC') {
             try {
                await writerDb.update(systemFeatures)
                  .set({ module: 'JVC' })
                  .where(inArray(systemFeatures.name, [
                    "Supreme's Eye (Multiverse)",
                    "Chronos Smart Scheduler",
                    "The Vault (Recordings)",
                    "Omniversal Multi-Stream",
                    "Ultra Breakout Matrix",
                    "Omniversal Multi-Stream & Ultra Breakout Matrix"
                  ]));
             } catch (migErr) {
                console.error("[AUTO-MIGRATION] Failed:", migErr);
             }
          }

          for (const feat of features) {
            if (!existingKeys.has(feat.key)) {
              await writerDb.insert(systemFeatures).values({
                module: m.module,
                key: feat.key,
                name: feat.name,
                description: feat.description || '',
                defaultState: feat.defaultState || 'UPSELL'
              });
              existingKeys.add(feat.key);
            }
          }
        }
      } catch (scanErr) {
        console.error(`[AUTO-SCANNER] Failed to parse manifest ${m.path}:`, scanErr);
      }
    }

    // Refetch after scanning
    const finalFeatures = await db.select().from(systemFeatures);
    return NextResponse.json({ features: finalFeatures });

  } catch (_e) {
    console.error("[SYSTEM FEATURES GET ERROR]", _e);
    return NextResponse.json({ error: 'Internal Error' }, { status: 500 });
  }
}

export async function POST(req: Request) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('jumpa_token')?.value;

    if (!token) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as { email: string; role: string };
    if (decoded.role !== 'superadmin') return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

    const { action, id } = await req.json();

    if (action === 'delete') {
      await writerDb.delete(systemFeatures).where(eq(systemFeatures.id, id));
      await writerDb.insert(quantumLogs).values({
        actor: decoded.email,
        action: 'DELETE_PARTICLE',
        targetId: id,
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
        userAgent: req.headers.get('user-agent') || 'Unknown'
      });
      return NextResponse.json({ success: true });
    }

    return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
  } catch (_e) {
    return NextResponse.json({ error: 'Internal Error' }, { status: 500 });
  }
}
