/**
 * Email verification API endpoint
 *
 * NOTE: This is a placeholder endpoint. Actual email verification is handled by
 * Supabase's built-in email verification flow (magic link sent on signup).
 * This endpoint exists for any additional verification-related logic (e.g.,
 * resending verification emails) but does not perform token validation itself.
 */

import { NextRequest, NextResponse } from 'next/server'
import { logger } from '@/lib/logger'
import { checkRateLimit, getClientIP, createRateLimitResponse } from '@/lib/rate-limit'
import { withCSRFProtection } from '@/lib/csrf'
import { createClient } from '@/lib/supabase/server'
import {
  VERIFY_RATE_LIMIT,
  VERIFY_WINDOW_MS,
  HTTP_STATUS_INTERNAL_SERVER_ERROR
} from '@/lib/constants'

const handler = async (request: NextRequest) => {
  try {
    // --- Auth check: require the user to be logged in ---
    const supabase = await createClient();
    const { data: { user }, error: authError } = await supabase.auth.getUser();

    if (authError || !user) {
      return NextResponse.json(
        { error: 'Unauthorized. You must be logged in to access this endpoint.' },
        { status: 401 }
      );
    }

    // --- Rate limiting (per-user + per-IP) ---
    const clientIP = getClientIP(request);
    const rateLimit = await checkRateLimit(`verify-email:${user.id}:${clientIP}`, VERIFY_RATE_LIMIT, VERIFY_WINDOW_MS);

    if (!rateLimit.allowed) {
      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
      return createRateLimitResponse(clientIP, retryAfter);
    }

    const { userId, token } = await request.json()

    if (!userId || !token) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 })
    }

    // This endpoint relies on Supabase's built-in email verification flow.
    // The actual verification happens when the user clicks the confirmation link
    // in the email sent by Supabase. This endpoint is a placeholder that returns
    // success — it does NOT independently validate tokens.

    return NextResponse.json({
      success: true,
      message: 'Email verification endpoint ready'
    })

  } catch (error) {
    logger.error('Email verification error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: HTTP_STATUS_INTERNAL_SERVER_ERROR }
    )
  }
}

// Apply CSRF protection to the handler
export const POST = withCSRFProtection(handler);
