import { Suspense } from 'react';
import { prisma } from '@/lib/db';
import { SearchContent } from './SearchContent';
import { PhotoGrid } from '@/components/PhotoGrid';

// Force dynamic rendering to prevent database queries during build
export const dynamic = 'force-dynamic';

async function getAllPeople() {
  try {
    return await prisma.person.findMany({
      select: {
        id: true,
        first_name: true,
        last_name: true,
        middle_name: true,
        maiden_name: true,
        date_of_birth: true,
        created_date: true,
      },
      orderBy: [
        { first_name: 'asc' },
        { last_name: 'asc' },
      ],
    });
  } catch (error: any) {
    // Handle corrupted data errors (P2023)
    if (error?.code === 'P2023' || error?.message?.includes('Conversion failed')) {
      console.warn('Corrupted person data detected, attempting fallback query');
      try {
        // Try with minimal fields first, but include all required fields for type compatibility
        return await prisma.person.findMany({
          select: {
            id: true,
            first_name: true,
            last_name: true,
            middle_name: true,
            maiden_name: true,
            date_of_birth: true,
            created_date: true,
          },
          orderBy: [
            { first_name: 'asc' },
            { last_name: 'asc' },
          ],
        });
      } catch (fallbackError: any) {
        console.error('Fallback person query also failed:', fallbackError);
        // Return empty array as last resort to prevent page crash
        return [];
      }
    }
    // Re-throw if it's a different error
    throw error;
  }
}

async function getAllTags() {
  try {
    return await prisma.tag.findMany({
      select: {
        id: true,
        tag_name: true,
        created_date: true,
      },
      orderBy: { tag_name: 'asc' },
    });
  } catch (error: any) {
    // Handle corrupted data errors (P2023)
    if (error?.code === 'P2023' || error?.message?.includes('Conversion failed')) {
      console.warn('Corrupted tag data detected, attempting fallback query');
      try {
        // Try with minimal fields, but include all required fields for type compatibility
        return await prisma.tag.findMany({
          select: {
            id: true,
            tag_name: true,
            created_date: true,
          },
          orderBy: { tag_name: 'asc' },
        });
      } catch (fallbackError: any) {
        console.error('Fallback tag query also failed:', fallbackError);
        // Return empty array as last resort to prevent page crash
        return [];
      }
    }
    // Re-throw if it's a different error
    throw error;
  }
}

export default async function SearchPage() {
  const [people, tags] = await Promise.all([
    getAllPeople(),
    getAllTags(),
  ]);

  return (
    <main className="w-full px-4 py-8">
      <div className="mb-8">
        <h1 className="text-4xl font-bold text-secondary dark:text-gray-50">
          Search Photos
        </h1>
        <p className="mt-2 text-gray-600 dark:text-gray-400">
          Find photos by people, dates, and tags
        </p>
      </div>

      <Suspense fallback={
        <div className="flex items-center justify-center py-12">
          <div className="text-gray-500">Loading search...</div>
        </div>
      }>
        <SearchContent people={people} tags={tags} />
      </Suspense>
    </main>
  );
}

