#!/usr/bin/env tsx
/**
 * Test script to identify which field is causing Prisma conversion errors
 */

import { PrismaClient } from '@prisma/client';
import * as dotenv from 'dotenv';

dotenv.config({ path: '.env' });

const prisma = new PrismaClient({
  log: ['error', 'warn'],
});

async function testQueries() {
  console.log('Testing different Prisma queries to identify the problematic field...\n');

  // Test 1: Query without date_of_birth
  console.log('Test 1: Query without date_of_birth field...');
  try {
    const result1 = await prisma.$queryRaw<Array<{
      id: number;
      first_name: string;
      last_name: string;
      created_date: Date;
    }>>`
      SELECT id, first_name, last_name, created_date
      FROM people
    `;
    console.log('✅ SUCCESS: Query without date_of_birth works');
    console.log(`   Found ${result1.length} record(s)\n`);
  } catch (e: any) {
    console.log('❌ FAILED:', e.message);
    console.log('');
  }

  // Test 2: Query with date_of_birth but cast it
  console.log('Test 2: Query with date_of_birth (as text)...');
  try {
    const result2 = await prisma.$queryRaw<Array<{
      id: number;
      first_name: string;
      last_name: string;
      date_of_birth: string | null;
      created_date: Date;
    }>>`
      SELECT id, first_name, last_name, 
             CAST(date_of_birth AS TEXT) as date_of_birth,
             created_date
      FROM people
    `;
    console.log('✅ SUCCESS: Query with date_of_birth as TEXT works');
    console.log(`   Found ${result2.length} record(s)`);
    for (const r of result2) {
      console.log(`   Person ${r.id}: date_of_birth = ${JSON.stringify(r.date_of_birth)}`);
    }
    console.log('');
  } catch (e: any) {
    console.log('❌ FAILED:', e.message);
    console.log('');
  }

  // Test 3: Query with date_of_birth using CASE to handle NULL
  console.log('Test 3: Query with date_of_birth (using CASE for NULL)...');
  try {
    const result3 = await prisma.$queryRaw<Array<{
      id: number;
      first_name: string;
      last_name: string;
      date_of_birth: string | null;
      created_date: Date;
    }>>`
      SELECT id, first_name, last_name,
             CASE 
               WHEN date_of_birth IS NULL THEN NULL
               ELSE CAST(date_of_birth AS TEXT)
             END as date_of_birth,
             created_date
      FROM people
    `;
    console.log('✅ SUCCESS: Query with date_of_birth using CASE works');
    console.log(`   Found ${result3.length} record(s)\n`);
  } catch (e: any) {
    console.log('❌ FAILED:', e.message);
    console.log('');
  }

  // Test 4: Try using findMany with select excluding date_of_birth
  console.log('Test 4: Prisma findMany without date_of_birth...');
  try {
    const result4 = await prisma.person.findMany({
      select: {
        id: true,
        first_name: true,
        last_name: true,
        middle_name: true,
        maiden_name: true,
        created_date: true,
        // Exclude date_of_birth
      },
    });
    console.log('✅ SUCCESS: Prisma findMany without date_of_birth works');
    console.log(`   Found ${result4.length} record(s)\n`);
  } catch (e: any) {
    console.log('❌ FAILED:', e.message);
    console.log('');
  }

  // Test 5: Try using findMany WITH date_of_birth
  console.log('Test 5: Prisma findMany WITH date_of_birth...');
  try {
    const result5 = await prisma.person.findMany({
      select: {
        id: true,
        first_name: true,
        last_name: true,
        middle_name: true,
        maiden_name: true,
        date_of_birth: true, // This is the problematic field
        created_date: true,
      },
    });
    console.log('✅ SUCCESS: Prisma findMany with date_of_birth works');
    console.log(`   Found ${result5.length} record(s)\n`);
  } catch (e: any) {
    console.log('❌ FAILED:', e.message);
    if (e.code === 'P2023') {
      console.log('   This confirms date_of_birth is the problematic field!\n');
    } else {
      console.log('');
    }
  }
}

testQueries()
  .then(() => {
    console.log('Tests complete.');
    process.exit(0);
  })
  .catch((e) => {
    console.error('Unexpected error:', e);
    process.exit(1);
  })
  .finally(() => {
    prisma.$disconnect();
  });




