/**
 * GET /api/promos — List Stripe promotion codes.
 * POST /api/promos — Create a Stripe coupon + promotion code.
 *
 * Uses Stripe's native Coupon + Promotion Code APIs.
 * No local DB needed — Stripe is the source of truth.
 */

import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { getCurrentUserFromRequest } from '@/lib/auth-server';
import * as growthClient from '@/lib/growth-client';
export async function GET(req: NextRequest) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    const url = new URL(req.url);
    const active = url.searchParams.get('active');
    const result = await growthClient.listPromos(active !== null ? active === 'true' : undefined);
    return NextResponse.json(result);
  } catch (error) {
    logError('List promos error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
export async function POST(req: NextRequest) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller || !['super_admin', 'admin'].includes(caller.role)) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }
    const body = await req.json();
    const {
      code,
      percentOff,
      amountOff,
      currency = 'usd',
      duration = 'once',
      durationInMonths,
      maxRedemptions,
      expiresAt,
    } = body;
    if (!code) {
      return NextResponse.json({ error: 'code is required' }, { status: 400 });
    }
    if (!percentOff && !amountOff) {
      return NextResponse.json(
        { error: 'Either percentOff or amountOff is required' },
        { status: 400 }
      );
    }
    const created = await growthClient.createPromo({
      code,
      percentOff,
      amountOff,
      currency,
      duration,
      durationInMonths,
      maxRedemptions,
      expiresAt,
      createdBy: caller.id,
    });
    return NextResponse.json(created, { status: 201 });
  } catch (error) {
    logError('Create promo error', error);
    const msg = error instanceof Error ? error.message : 'Internal server error';
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
