/**
 * Promo by ID — proxies to platform-service promo endpoints.
 *
 * DELETE /api/promos/:id  → deactivate promo (Stripe promos cannot be deleted, only deactivated)
 * PATCH  /api/promos/:id  → deactivate promo (toggle off)
 */

import { NextRequest, NextResponse } from 'next/server';
import { getCurrentUserFromRequest } from '@/lib/auth-server';
import { deactivatePromo } from '@/lib/growth-client';
import { logError } from '@/lib/logger';

type RouteContext = { params: Promise<{ id: string }> };

export async function DELETE(req: NextRequest, ctx: RouteContext) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller || !['super_admin', 'admin'].includes(caller.role)) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }
    const { id } = await ctx.params;
    await deactivatePromo(id);
    return NextResponse.json({ success: true });
  } catch (error) {
    logError('Promo delete error', error);
    return NextResponse.json({ error: 'Failed to deactivate promo' }, { status: 500 });
  }
}

export async function PATCH(req: NextRequest, ctx: RouteContext) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller || !['super_admin', 'admin'].includes(caller.role)) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }
    const { id } = await ctx.params;
    const body = await req.json();
    // Only deactivation is supported by Stripe — active: false
    if (body.active === false) {
      const result = await deactivatePromo(id);
      return NextResponse.json(result);
    }
    // Stripe promotion codes cannot be re-activated once deactivated
    return NextResponse.json(
      { error: 'Stripe promotion codes cannot be re-activated once deactivated' },
      { status: 400 }
    );
  } catch (error) {
    logError('Promo update error', error);
    return NextResponse.json({ error: 'Failed to update promo' }, { status: 500 });
  }
}
