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

// POST - Verify/update a payment status (admin or system callback)
export async function POST(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission(request, 'canManageOrders');
    if ('error' in authResult) return authResult.error;

    const body = await request.json();
    const { transactionId, status, gatewayTransactionId, gatewayResponse } = body;

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

    const validStatuses = ['pending', 'processing', 'completed', 'failed', 'refunded'];
    if (!validStatuses.includes(status)) {
      return NextResponse.json({ success: false, error: `Invalid status. Must be one of: ${validStatuses.join(', ')}` }, { status: 400 });
    }

    const existing = await db.paymentTransaction.findUnique({ where: { id: transactionId } });
    if (!existing) {
      return NextResponse.json({ success: false, error: 'Transaction not found' }, { status: 404 });
    }

    const updateData: Record<string, unknown> = { status };
    if (gatewayTransactionId) updateData.transactionId = gatewayTransactionId;
    if (gatewayResponse) updateData.gatewayResponse = typeof gatewayResponse === 'object' ? JSON.stringify(gatewayResponse) : gatewayResponse;

    const transaction = await db.paymentTransaction.update({
      where: { id: transactionId },
      data: updateData,
    });

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