import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getCurrentUser } from '@/lib/auth';

export async function POST(req: Request) {
    try {
        const user = await getCurrentUser();
        if (!user || !['admin', 'super_admin'].includes(user.role)) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        const { batchId } = await req.json();
        if (!batchId) {
            return NextResponse.json({ error: 'Batch ID required' }, { status: 400 });
        }

        // 1. Find all audit logs for this batch
        // We use queryRaw or JSON search if available, but for simplicity here
        // we'll filter in application logic if needed, or use a specific format
        const logs = await prisma.auditLog.findMany({
            where: {
                user_id: user.id,
                action: { startsWith: 'job.bulk_' }
                // Note: Filtering by JSON batchId is provider-specific in Prisma
                // For SQLite/Postgres we can use path:
            }
        });

        // Filter logs that actually have this batchId in details
        const batchLogs = logs.filter((log: any) =>
            log.details && (log.details as any).batchId === batchId
        );

        if (batchLogs.length === 0) {
            return NextResponse.json({ error: 'Batch not found or already expired' }, { status: 404 });
        }

        const jobIds = batchLogs
            .map(log => log.resource_id)
            .filter((id): id is string => id !== null);

        // 2. Revert Jobs to 'pending'
        const count = await prisma.$transaction(async (tx) => {
            const updated = await tx.job.updateMany({
                where: { id: { in: jobIds } },
                data: {
                    status: 'pending',
                    updated_at: new Date()
                }
            });

            // Log the undo action
            await tx.auditLog.create({
                data: {
                    action: 'job.bulk_undo',
                    resource_type: 'batch',
                    resource_id: batchId,
                    user_id: user.id,
                    details: {
                        originalBatchId: batchId,
                        revertedCount: updated.count,
                        timestamp: new Date().toISOString()
                    }
                }
            });

            return updated.count;
        });

        return NextResponse.json({
            success: true,
            count,
            message: `Successfully reverted ${count} jobs to pending status`
        });

    } catch (error: any) {
        console.error('Bulk undo error:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}
