#!/usr/bin/env node
// Test script to verify MCP server can connect to the database

import { PrismaClient } from '@prisma/client';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

console.log('🧪 Testing MCP Server Database Connection...\n');

try {
  const prisma = new PrismaClient({
    datasources: {
      db: {
        url: 'file:D:/dev_new_pc/Keep/memento-note/prisma/dev.db'
      }
    }
  });

  console.log('✅ Prisma Client initialized successfully');

  // Test 1: Count notes
  console.log('\n📝 Test 1: Counting notes...');
  const noteCount = await prisma.note.count();
  console.log(`   Found ${noteCount} notes in database`);

  // Test 2: Get recent notes
  console.log('\n📝 Test 2: Fetching recent notes...');
  const recentNotes = await prisma.note.findMany({
    take: 3,
    orderBy: { updatedAt: 'desc' }
  });
  console.log(`   Fetched ${recentNotes.length} recent notes`);
  if (recentNotes.length > 0) {
    console.log(`   Latest note: ${recentNotes[0].title || 'Untitled'}`);
  }

  // Test 3: Count notebooks
  console.log('\n📚 Test 3: Counting notebooks...');
  const notebookCount = await prisma.notebook.count();
  console.log(`   Found ${notebookCount} notebooks in database`);

  // Test 4: Get notebooks
  console.log('\n📚 Test 4: Fetching notebooks...');
  const notebooks = await prisma.notebook.findMany({
    take: 3,
    orderBy: { order: 'asc' }
  });
  console.log(`   Fetched ${notebooks.length} notebooks`);
  if (notebooks.length > 0) {
    notebooks.forEach(nb => {
      console.log(`   - ${nb.icon || '📁'} ${nb.name}`);
    });
  }

  // Test 5: Count labels
  console.log('\n🏷️  Test 5: Counting labels...');
  const labelCount = await prisma.label.count();
  console.log(`   Found ${labelCount} labels in database`);

  // Test 6: Get labels
  console.log('\n🏷️  Test 6: Fetching labels...');
  const labels = await prisma.label.findMany({
    take: 5,
    orderBy: { name: 'asc' }
  });
  console.log(`   Fetched ${labels.length} labels`);
  if (labels.length > 0) {
    labels.forEach(l => {
      console.log(`   - ${l.name} (${l.color})`);
    });
  }

  await prisma.$disconnect();
  console.log('\n✅ All database tests passed successfully!');
  console.log('🚀 MCP Server is ready to use!\n');

} catch (error) {
  console.error('\n❌ Database test failed:', error.message);
  console.error(error);
  process.exit(1);
}
