/**
 * QR Code Generation API Endpoint
 * POST /api/qr-code/generate
 */

import { NextRequest, NextResponse } from 'next/server';
import { QRCalculatorData, QRGenerationResponse } from '@/src/types';
import { validateQRData, sanitizeQRData } from '@/src/utils/qrDataValidator';
import { generateCalculatorQRCode } from '@/src/utils/qrCodeGenerator';

export async function POST(request: NextRequest) {
  console.log('[QR API] POST /api/qr-code/generate - Request received');

  try {
    // Parse request body
    const body = await request.json();
    console.log('[QR API] Request body parsed:', JSON.stringify(body, null, 2));

    // Validate data
    console.log('[QR API] Validating QR data...');
    const validationResult = validateQRData(body);

    if (!validationResult.valid) {
      console.error('[QR API] Validation failed:', validationResult.error);
      return NextResponse.json(
        {
          success: false,
          error: validationResult.error || 'Invalid QR data',
        },
        { status: 400 }
      );
    }
    console.log('[QR API] Validation successful');

    const data = validationResult.data as QRCalculatorData;

    // Sanitize data to remove any unnecessary fields
    const cleanedData = sanitizeQRData(data);
    console.log('[QR API] Data sanitized');

    // Get base URL from request
    const protocol = request.headers.get('x-forwarded-proto') || 'https';
    const host = request.headers.get('host') || 'localhost:3000';
    const baseUrl = `${protocol}://${host}`;
    console.log('[QR API] Base URL:', baseUrl);

    // Generate QR code
    console.log('[QR API] Generating QR code...');
    const { dataURL, svg, url } = await generateCalculatorQRCode(cleanedData, baseUrl);
    console.log('[QR API] QR code generated successfully, URL:', url);

    // Set expiration time (30 days from now)
    const expiresAt = new Date();
    expiresAt.setDate(expiresAt.getDate() + 30);

    // Prepare response
    const response: QRGenerationResponse = {
      qrCodeDataURL: dataURL,
      qrCodeSVG: svg,
      url: url,
      expiresAt: expiresAt.toISOString(),
    };

    console.log('[QR API] Sending success response');
    return NextResponse.json({
      success: true,
      data: response,
    });
  } catch (error) {
    console.error('[QR API] Error generating QR code:', error);
    console.error('[QR API] Error stack:', error instanceof Error ? error.stack : 'No stack trace');

    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to generate QR code',
      },
      { status: 500 }
    );
  }
}

// Return method not allowed for other HTTP methods
export async function GET() {
  console.log('[QR API] GET /api/qr-code/generate - Method not allowed');
  return NextResponse.json(
    {
      success: false,
      error: 'Method not allowed. Use POST to generate QR codes.',
    },
    { status: 405 }
  );
}
