← back to Wine Finder Next

app/api/membership/votes/[id]/execute/route.ts

80 lines

import { NextRequest, NextResponse } from 'next/server';
import { governanceVoteDb } from '@/lib/membershipDatabase';
import type { ApiResponse } from '@/src/types/membership';
import { checkRateLimit, getRateLimitConfig, getClientIdentifier } from '@/lib/rateLimit';
import { logAudit } from '@/lib/auth';
import { sanitizeString, validateVoteId } from '@/lib/inputValidation';

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    // Rate limiting
    const identifier = getClientIdentifier(request);
    const rateLimit = checkRateLimit(identifier, getRateLimitConfig('/api/membership/votes'));

    if (!rateLimit.success) {
      return NextResponse.json({
        success: false,
        error: 'Rate limit exceeded. Please try again later.'
      } as ApiResponse<null>, { status: 429 });
    }

    // Validate vote ID
    const sanitizedId = sanitizeString(id, 100);
    if (!validateVoteId(sanitizedId)) {
      return NextResponse.json({
        success: false,
        error: 'Invalid vote ID format'
      } as ApiResponse<null>, { status: 400 });
    }

    const result = governanceVoteDb.executeVote(sanitizedId);

    if (!result) {
      logAudit({
        action: 'VOTE_EXECUTE_NOT_FOUND',
        resource: `vote/${sanitizedId}`,
        ipAddress: identifier,
        userAgent: request.headers.get('user-agent') || 'unknown',
        success: false
      });

      return NextResponse.json({
        success: false,
        error: 'Vote not found'
      } as ApiResponse<null>, { status: 404 });
    }

    logAudit({
      action: 'VOTE_EXECUTE',
      resource: `vote/${sanitizedId}`,
      ipAddress: identifier,
      userAgent: request.headers.get('user-agent') || 'unknown',
      success: true,
      metadata: {
        voteId: sanitizedId,
        status: result.status,
        forVotes: result.votesFor,
        againstVotes: result.votesAgainst
      }
    });

    return NextResponse.json({
      success: true,
      data: result,
      message: result.status === 'passed'
        ? 'Vote passed and executed successfully'
        : 'Vote failed to meet quorum or approval threshold'
    });
  } catch (error) {
    return NextResponse.json({
      success: false,
      error: 'Failed to execute vote'
    } as ApiResponse<null>, { status: 500 });
  }
}