import { prisma } from '@/lib/core/prisma';
import { createLogger } from '@/lib/core/logger';
import { createMeasuredJsonResponse, createRoutePerfTracker } from '@/lib/core/route-perf';
import { guardTestCaseRouteRequest } from '@/lib/security/test-case-route-access';
import { apiError } from '@/lib/security/api-route-standards';

const logger = createLogger('api:test-cases:history');

export async function GET(
    request: Request,
    { params }: { params: Promise<{ id: string }> }
) {
    const perf = createRoutePerfTracker('/api/test-cases/[id]/history', request);
    const guard = await perf.measureAuth(() => guardTestCaseRouteRequest({ request, params }));
    if (!guard.ok) {
        const responseBytes = new TextEncoder().encode(await guard.response.clone().text()).length;
        perf.log(logger, { statusCode: guard.response.status, responseBytes });
        return guard.response;
    }

    try {
        const { id } = guard.params;
        const url = new URL(request.url);
        const page = Math.max(1, parseInt(url.searchParams.get('page') || '1'));
        const limit = Math.min(100, Math.max(1, parseInt(url.searchParams.get('limit') || '20')));
        const skip = (page - 1) * limit;
        const includePayload = url.searchParams.get('includePayload') === '1';

        const testRunsPromise = includePayload
            ? prisma.testRun.findMany({
                where: {
                    testCaseId: id,
                    deletedAt: null,
                },
                orderBy: { createdAt: 'desc' },
                include: { files: true },
                skip,
                take: limit
            })
            : prisma.testRun.findMany({
                where: {
                    testCaseId: id,
                    deletedAt: null,
                },
                orderBy: { createdAt: 'desc' },
                select: {
                    id: true,
                    status: true,
                    createdAt: true,
                    error: true,
                    triggeredByEmail: true,
                    triggerSource: true,
                    instanceId: true,
                    instanceType: true,
                    instanceName: true,
                },
                skip,
                take: limit
            });

        const [testRuns, total] = await perf.measureDb(() => Promise.all([
            testRunsPromise,
            prisma.testRun.count({
                where: {
                    testCaseId: id,
                    deletedAt: null,
                },
            })
        ]));

        const body = {
            data: testRuns,
            pagination: { page, limit, total, totalPages: Math.ceil(total / limit) }
        };
        const { response, responseBytes } = createMeasuredJsonResponse(body);
        perf.log(logger, { statusCode: 200, responseBytes });
        return response;
    } catch (error) {
        logger.error('Failed to fetch test history', error);
        const response = apiError({
            status: 500,
            code: 'INTERNAL_ERROR',
            error: 'Failed to fetch test history',
        });
        const responseBytes = new TextEncoder().encode(await response.clone().text()).length;
        perf.log(logger, { statusCode: 500, responseBytes });
        return response;
    }
}
