/**
 * Recent WhatsApp message log (paginated cap = 100).
 * GET /api/channels/whatsapp/log?branch_id=...&limit=...
 */
import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { listRecentMessages, restaurantHasWhatsAppFeature } from '@server/services/whatsapp.service';

// Message log can contain customer phone numbers and message bodies —
// PII-sensitive and reserved for restaurant management roles.
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 GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const denied = requireAdmin(req);
    if (denied) return denied;
    await requireSection(req, 'whatsapp');
    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 url = new URL(req.url);
    const branchId = url.searchParams.get('branch_id');
    const limit = Number(url.searchParams.get('limit') || '30');
    const messages = await listRecentMessages(restaurantId, branchId, isFinite(limit) ? limit : 30);
    return NextResponse.json({ messages });
  })
);
