import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyUserAuth } from '@/lib/auth';

// POST - Initiate a payment (creates a PaymentTransaction)
// Requires user authentication via x-user-token header
export async function POST(request: NextRequest) {
  try {
    // Verify user is authenticated
    const authResult = await verifyUserAuth(request);
    if ('error' in authResult) return authResult.error;

    const { session } = authResult;
    const body = await request.json();
    const { gatewayId, orderId, amount, currency, metadata } = body;

    // Use the authenticated user's ID from the session token (ignore any userId in body)
    const userId = session.id;

    if (!gatewayId || !amount) {
      return NextResponse.json({ success: false, error: 'gatewayId and amount are required' }, { status: 400 });
    }

    // Validate amount is a positive number
    const parsedAmount = parseFloat(String(amount));
    if (isNaN(parsedAmount) || parsedAmount <= 0) {
      return NextResponse.json({ success: false, error: 'Amount must be a positive number' }, { status: 400 });
    }

    // Verify gateway exists and is active
    const gateway = await db.paymentGateway.findUnique({ where: { id: gatewayId } });
    if (!gateway) {
      return NextResponse.json({ success: false, error: 'Payment gateway not found' }, { status: 404 });
    }
    if (!gateway.isActive) {
      return NextResponse.json({ success: false, error: 'Payment gateway is not active' }, { status: 400 });
    }

    const transaction = await db.paymentTransaction.create({
      data: {
        userId,
        gatewayId,
        orderId: orderId || null,
        amount: parsedAmount,
        currency: currency || 'BDT',
        status: 'pending',
        metadata: typeof metadata === 'object' ? JSON.stringify(metadata) : (metadata || '{}'),
      },
    });

    return NextResponse.json({ success: true, transaction }, { status: 201 });
  } catch (error) {
    console.error('Payment initiate error:', error);
    return NextResponse.json({ success: false, error: 'Failed to initiate payment' }, { status: 500 });
  }
}

// GET - Get payment history for the authenticated user
// Requires user authentication via x-user-token header
export async function GET(request: NextRequest) {
  try {
    // Verify user is authenticated
    const authResult = await verifyUserAuth(request);
    if ('error' in authResult) return authResult.error;

    const { session } = authResult;
    // Use the authenticated user's ID from the session token (ignore any userId in query)
    const userId = session.id;

    const transactions = await db.paymentTransaction.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
      include: {
        gateway: {
          select: { id: true, name: true, icon: true, type: true },
        },
      },
    });

    return NextResponse.json({ success: true, transactions });
  } catch (error) {
    console.error('Payment history fetch error:', error);
    return NextResponse.json({ success: false, error: 'Failed to fetch payment history' }, { status: 500 });
  }
}
