import { NextResponse } from 'next/server';
import { existsSync } from 'fs';
import path from 'path';
import { getDatabase } from '@/db';

export async function GET() {
  try {
    // Check if database is accessible by actually connecting to it
    try {
      const db = getDatabase();
      // Test a simple query
      db.prepare('SELECT 1').get();
    } catch (dbError) {
      return NextResponse.json(
        { status: 'unhealthy', error: `Database not accessible: ${(dbError as Error).message}` },
        { status: 503 }
      );
    }

    // Check if media directory is accessible
    const mediaRoot = process.env.NEXT_PUBLIC_MEDIA_ROOT || '/app/media';
    if (!existsSync(mediaRoot)) {
      return NextResponse.json(
        { status: 'unhealthy', error: 'Media directory not accessible' },
        { status: 503 }
      );
    }

    return NextResponse.json({ status: 'healthy' });
  } catch (error) {
    return NextResponse.json(
      { status: 'unhealthy', error: (error as Error).message },
      { status: 500 }
    );
  }
}