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

/**
 * Health check endpoint that verifies database connectivity and permissions
 * This runs automatically and can help detect permission issues early
 */
export async function GET() {
  const checks: Record<string, { status: 'ok' | 'error'; message: string }> = {};

  // Check database connection
  try {
    await prisma.$connect();
    checks.database_connection = {
      status: 'ok',
      message: 'Database connection successful',
    };
  } catch (error: any) {
    checks.database_connection = {
      status: 'error',
      message: `Database connection failed: ${error.message}`,
    };
    return NextResponse.json(
      {
        status: 'error',
        checks,
        message: 'Database health check failed',
      },
      { status: 503 }
    );
  }

  // Check permissions on key tables
  const tables = [
    { name: 'photos', query: () => prisma.photo.findFirst() },
    { name: 'people', query: () => prisma.person.findFirst() },
    { name: 'faces', query: () => prisma.face.findFirst() },
    { name: 'tags', query: () => prisma.tag.findFirst() },
  ];

  for (const table of tables) {
    try {
      await table.query();
      checks[`table_${table.name}`] = {
        status: 'ok',
        message: `SELECT permission on ${table.name} table is OK`,
      };
    } catch (error: any) {
      if (error.message?.includes('permission denied')) {
        checks[`table_${table.name}`] = {
          status: 'error',
          message: `Permission denied on ${table.name} table. Run grant_readonly_permissions.sql as superuser.`,
        };
      } else {
        checks[`table_${table.name}`] = {
          status: 'error',
          message: `Error accessing ${table.name}: ${error.message}`,
        };
      }
    }
  }

  const hasErrors = Object.values(checks).some((check) => check.status === 'error');

  return NextResponse.json(
    {
      status: hasErrors ? 'error' : 'ok',
      checks,
      timestamp: new Date().toISOString(),
      ...(hasErrors && {
        fixInstructions: {
          message: 'To fix permission errors, run as PostgreSQL superuser:',
          command: 'psql -U postgres -d punimtag -f grant_readonly_permissions.sql',
        },
      }),
    },
    { status: hasErrors ? 503 : 200 }
  );
}








