import { NextResponse } from 'next/server';

import { checkDatabaseHealth } from '@/lib/core/prisma';
import { createLogger } from '@/lib/core/logger';
import { checkObjectStoreHealth } from '@/lib/storage/object-store';

type ReadinessCheckStatus = 'ok' | 'error';

interface ReadinessCheckResult {
    status: ReadinessCheckStatus;
    error?: string;
}

const logger = createLogger('api:health:ready');

function getErrorMessage(error: unknown): string {
    logger.warn('Readiness dependency check failed', error);
    return 'Dependency unavailable';
}

async function runReadinessCheck(check: () => Promise<void>): Promise<ReadinessCheckResult> {
    try {
        await check();
        return { status: 'ok' };
    } catch (error) {
        return {
            status: 'error',
            error: getErrorMessage(error),
        };
    }
}

export async function GET() {
    const [database, storage] = await Promise.all([
        runReadinessCheck(checkDatabaseHealth),
        runReadinessCheck(checkObjectStoreHealth),
    ]);

    const status = database.status === 'ok' ? 'ok' : 'error';
    const dependenciesStatus = storage.status === 'ok' ? 'ok' : 'degraded';

    return NextResponse.json(
        {
            status,
            dependenciesStatus,
            checks: {
                database,
                dependencies: {
                    storage,
                },
            },
        },
        { status: status === 'ok' ? 200 : 503 }
    );
}
