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

// GET - List all payment gateways (admin)
export async function GET(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission(request, 'canManageOrders');
    if ('error' in authResult) return authResult.error;

    const gateways = await db.paymentGateway.findMany({
      orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
    });

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

// POST - Create a new payment gateway
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 { name, slug, type, icon, description, config, instructions, isActive, sortOrder } = body;

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

    // Check for duplicate slug
    const existing = await db.paymentGateway.findUnique({ where: { slug } });
    if (existing) {
      return NextResponse.json({ success: false, error: 'A gateway with this slug already exists' }, { status: 409 });
    }

    const gateway = await db.paymentGateway.create({
      data: {
        name,
        slug,
        type: type || 'custom',
        icon: icon || null,
        description: description || null,
        config: typeof config === 'object' ? JSON.stringify(config) : (config || '{}'),
        instructions: instructions || '',
        isActive: typeof isActive === 'boolean' ? isActive : false,
        sortOrder: typeof sortOrder === 'number' ? sortOrder : 0,
        isSystem: false,
      },
    });

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

// PATCH - Update a payment gateway
export async function PATCH(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission(request, 'canManageOrders');
    if ('error' in authResult) return authResult.error;

    const body = await request.json();
    const { gatewayId, name, slug, type, icon, description, config, instructions, isActive, sortOrder } = body;

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

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

    // If slug is being changed, check for conflicts
    if (slug && slug !== existing.slug) {
      const slugConflict = await db.paymentGateway.findUnique({ where: { slug } });
      if (slugConflict) {
        return NextResponse.json({ success: false, error: 'A gateway with this slug already exists' }, { status: 409 });
      }
    }

    const updateData: Record<string, unknown> = {};
    if (name !== undefined) updateData.name = name;
    if (slug !== undefined) updateData.slug = slug;
    if (type !== undefined) updateData.type = type;
    if (icon !== undefined) updateData.icon = icon;
    if (description !== undefined) updateData.description = description;
    if (config !== undefined) updateData.config = typeof config === 'object' ? JSON.stringify(config) : config;
    if (instructions !== undefined) updateData.instructions = instructions;
    if (typeof isActive === 'boolean') updateData.isActive = isActive;
    if (typeof sortOrder === 'number') updateData.sortOrder = sortOrder;

    const gateway = await db.paymentGateway.update({
      where: { id: gatewayId },
      data: updateData,
    });

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

// DELETE - Delete a custom payment gateway (system gateways can't be deleted)
export async function DELETE(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission(request, 'canManageOrders');
    if ('error' in authResult) return authResult.error;

    const { gatewayId } = await request.json();
    if (!gatewayId) {
      return NextResponse.json({ success: false, error: 'gatewayId is required' }, { status: 400 });
    }

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

    if (existing.isSystem) {
      return NextResponse.json({ success: false, error: 'System gateways cannot be deleted. You can only deactivate them.' }, { status: 403 });
    }

    await db.paymentGateway.delete({ where: { id: gatewayId } });
    return NextResponse.json({ success: true, message: 'Payment gateway deleted' });
  } catch (error) {
    console.error('Payment gateway delete error:', error);
    return NextResponse.json({ success: false, error: 'Failed to delete payment gateway' }, { status: 500 });
  }
}
