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

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 { email: string; role: string };
    if (decoded.role !== 'superadmin') return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

    const packages = await db.select().from(saasPackages);
    const systemFeaturesList = await db.select().from(systemFeatures);
    return NextResponse.json({ packages, systemFeatures: systemFeaturesList });
  } catch (_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, name, price, features, isHidden } = await req.json();

    if (action === 'create') {
      await writerDb.insert(saasPackages).values({
        name,
        price,
        features: JSON.stringify(features),
        isHidden: !!isHidden
      });
      await writerDb.insert(quantumLogs).values({
        actor: decoded.email,
        action: 'CREATE_PACKAGE',
        targetId: name,
        ipAddress: req.headers.get('x-forwarded-for') || '127.0.0.1',
        userAgent: req.headers.get('user-agent') || 'Unknown'
      });
      return NextResponse.json({ success: true });
    }

    if (action === 'update') {
      await writerDb.update(saasPackages)
        .set({
          name,
          price,
          features: JSON.stringify(features),
          isHidden: !!isHidden
        })
        .where(eq(saasPackages.id, id));
        
      await writerDb.insert(quantumLogs).values({
        actor: decoded.email,
        action: 'UPDATE_PACKAGE',
        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 });
    }

    if (action === 'delete') {
      await writerDb.delete(saasPackages).where(eq(saasPackages.id, id));
      await writerDb.insert(quantumLogs).values({
        actor: decoded.email,
        action: 'DELETE_PACKAGE',
        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 });
  }
}
