import { NextRequest, NextResponse } from 'next/server';
import { requireAdmin } from '@/lib/auth-server';
import {
  getUserLicenses,
  generateLicense,
  revokeLicense,
  deactivateLicenseDevice,
} from '@/lib/billing-client';

export async function GET(req: NextRequest) {
  const admin = await requireAdmin(req);
  if (!admin) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const userId = req.nextUrl.searchParams.get('userId');
  if (!userId) return NextResponse.json({ error: 'userId is required' }, { status: 400 });

  try {
    const result = await getUserLicenses(userId);
    return NextResponse.json(result);
  } catch (err) {
    return NextResponse.json({ error: String(err) }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  const admin = await requireAdmin(req);
  if (!admin) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  try {
    const body = await req.json();

    if (body.action === 'revoke' && body.key) {
      const result = await revokeLicense(body.key);
      return NextResponse.json(result);
    }

    if (body.action === 'deactivate' && body.key && body.deviceId) {
      const result = await deactivateLicenseDevice(body.key, body.deviceId);
      return NextResponse.json(result);
    }

    // Default: generate new license
    const license = await generateLicense(body);
    return NextResponse.json(license, { status: 201 });
  } catch (err) {
    return NextResponse.json({ error: String(err) }, { status: 500 });
  }
}
