/**
 * Test a saved WhatsApp credential by hitting Meta's phone-number node.
 * POST /api/channels/whatsapp/test  { branch_id }
 */
import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { testWhatsAppConnection, restaurantHasWhatsAppFeature } from '@server/services/whatsapp.service';

// Test connection burns Graph API quota and reveals branch credential
// validity — restricted to admin roles, same as the credentials endpoints.
function requireAdmin(req: AuthedRequest): NextResponse | null {
  const role = req.session?.role;
  if (role !== 'owner' && role !== 'manager' && role !== 'superadmin') {
    return NextResponse.json(
      { error: 'Owner or manager access required' },
      { status: 403 }
    );
  }
  return null;
}

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const denied = requireAdmin(req);
    if (denied) return denied;
    await requireSection(req, 'whatsapp', 'create');
    const { restaurantId } = req.session;
    if (!restaurantId) return NextResponse.json({ error: 'Restaurant context required' }, { status: 400 });
    const has = await restaurantHasWhatsAppFeature(restaurantId);
    if (!has) {
      return NextResponse.json(
        { error: 'WhatsApp Business is not included in your plan.', code: 'PLAN_UPGRADE_REQUIRED' },
        { status: 402 }
      );
    }
    const body = await req.json().catch(() => ({})) as Record<string, unknown>;
    const branchId = typeof body.branch_id === 'string' ? body.branch_id : '';
    if (!branchId) return NextResponse.json({ error: 'branch_id is required' }, { status: 400 });
    const result = await testWhatsAppConnection(restaurantId, branchId);
    if (!result.ok) {
      return NextResponse.json(
        { ok: false, error: result.error.message, status: result.error.status },
        { status: 200 }
      );
    }
    return NextResponse.json({
      ok: true,
      display_phone_number: result.displayPhoneNumber,
      verified_name: result.verifiedName,
      waba_name: result.wabaName,
    });
  })
);
