/// <reference types="@cloudflare/workers-types" />

export interface Env {
  HYPERDRIVE: Hyperdrive;
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    try {
      // Test Hyperdrive connection to NeonDB
      const { pathname } = new URL(request.url);
      
      if (pathname === '/test-connection') {
        return await testConnection(env);
      }
      
      if (pathname === '/test-query') {
        return await testQuery(env);
      }
      
      if (pathname === '/query-tables') {
        return await queryTables(env);
      }
      
      if (pathname === '/query-shushu') {
        const url = new URL(request.url);
        const limit = parseInt(url.searchParams.get('limit') || '10');
        return await queryShushuBook(env, limit);
      }
      
      if (pathname === '/search-shushu') {
        const url = new URL(request.url);
        const keyword = url.searchParams.get('q') || '';
        const limit = parseInt(url.searchParams.get('limit') || '5');
        return await searchShushuBook(env, keyword, limit);
      }
      
      if (pathname === '/shushu-stats') {
        return await getShushuStats(env);
      }
      
      return new Response('Hyperdrive NeonDB Test Worker\n\nEndpoints:\n- /test-connection - Test database connection\n- /test-query - Test database query\n- /query-tables - List all tables\n- /query-shushu?limit=N - Query shushu book content\n- /search-shushu?q=keyword&limit=N - Search shushu book\n- /shushu-stats - Get shushu book statistics', {
        headers: { 'Content-Type': 'text/plain' }
      });
    } catch (error) {
      return new Response(`Error: ${error.message}`, { 
        status: 500,
        headers: { 'Content-Type': 'text/plain' }
      });
    }
  },
};

async function testConnection(env: Env): Promise<Response> {
  try {
    // Get connection string from Hyperdrive
    const connectionString = env.HYPERDRIVE.connectionString;
    
    // Create a simple connection test
    const { Client } = await import('pg');
    const client = new Client({ connectionString });
    
    await client.connect();
    
    // Test basic query
    const result = await client.query('SELECT NOW() as current_time, version() as pg_version');
    
    await client.end();
    
    return new Response(JSON.stringify({
      status: 'success',
      message: 'Successfully connected to NeonDB via Hyperdrive',
      data: result.rows[0],
      connectionInfo: {
        hyperdrive_id: 'ef43924d89064cddabfaccf06aadfab6',
        connection_pooled: true
      }
    }, null, 2), {
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({
      status: 'error',
      message: 'Failed to connect to NeonDB',
      error: error.message
    }, null, 2), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

// 查询数据库表结构
async function queryTables(env: Env): Promise<Response> {
  try {
    const { Client } = await import('pg');
    const client = new Client({ 
      connectionString: env.HYPERDRIVE.connectionString 
    });
    
    await client.connect();
    
    // 查询所有表
    const result = await client.query(`
      SELECT table_name, table_schema 
      FROM information_schema.tables 
      WHERE table_schema NOT IN ('information_schema', 'pg_catalog')
      ORDER BY table_schema, table_name
    `);
    
    await client.end();
    
    return new Response(JSON.stringify({
      status: 'success',
      message: 'Tables retrieved successfully',
      tables: result.rows
    }, null, 2), {
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({
      status: 'error',
      message: 'Failed to query tables',
      error: error.message
    }, null, 2), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

// 查询术数书内容
async function queryShushuBook(env: Env, limit: number = 10): Promise<Response> {
  try {
    const { Client } = await import('pg');
    const client = new Client({ 
      connectionString: env.HYPERDRIVE.connectionString 
    });
    
    await client.connect();
    
    // 尝试查询可能的术数书表名
     const tableNames = ['shushu', 'shushu_book', 'books', 'articles', 'content', 'documents'];
     let result: any = null;
     let tableName: string | null = null;
    
    for (const name of tableNames) {
      try {
        const testResult = await client.query(`SELECT * FROM ${name} LIMIT 1`);
        if (testResult.rows.length > 0) {
          tableName = name;
          result = await client.query(`SELECT * FROM ${name} ORDER BY id DESC LIMIT $1`, [limit]);
          break;
        }
      } catch (e) {
        // 表不存在，继续尝试下一个
        continue;
      }
    }
    
    await client.end();
    
    if (!result) {
      return new Response(JSON.stringify({
        status: 'error',
        message: 'No shushu book table found',
        searched_tables: tableNames
      }, null, 2), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    return new Response(JSON.stringify({
      status: 'success',
      message: 'Shushu book content retrieved successfully',
      table_name: tableName,
      count: result.rows.length,
      data: result.rows
    }, null, 2), {
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({
      status: 'error',
      message: 'Failed to query shushu book',
      error: error.message
    }, null, 2), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

// 搜索术数书内容
async function searchShushuBook(env: Env, keyword: string, limit: number = 5): Promise<Response> {
  try {
    if (!keyword) {
      return new Response(JSON.stringify({
        status: 'error',
        message: 'Search keyword is required'
      }, null, 2), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { Client } = await import('pg');
    const client = new Client({ 
      connectionString: env.HYPERDRIVE.connectionString 
    });
    
    await client.connect();
    
    // 尝试在不同的表和字段中搜索
    const searchQueries = [
      { table: 'shushu', fields: ['title', 'content', 'description'] },
      { table: 'shushu_book', fields: ['title', 'content', 'text'] },
      { table: 'books', fields: ['title', 'content', 'description'] },
      { table: 'articles', fields: ['title', 'content', 'body'] },
      { table: 'content', fields: ['title', 'text', 'content'] },
      { table: 'documents', fields: ['title', 'content', 'text'] }
    ];
    
    let results: any[] = [];
     let searchedTables: string[] = [];
    
    for (const { table, fields } of searchQueries) {
      try {
        // 构建搜索条件
        const conditions = fields.map(field => `${field} ILIKE $1`).join(' OR ');
        const query = `SELECT * FROM ${table} WHERE ${conditions} LIMIT $2`;
        
        const result = await client.query(query, [`%${keyword}%`, limit]);
        
        if (result.rows.length > 0) {
          results.push({
            table_name: table,
            count: result.rows.length,
            data: result.rows
          });
        }
        
        searchedTables.push(table);
      } catch (e) {
        // 表或字段不存在，继续搜索
        continue;
      }
    }
    
    await client.end();
    
    return new Response(JSON.stringify({
      status: 'success',
      message: `Search completed for keyword: ${keyword}`,
      keyword: keyword,
      searched_tables: searchedTables,
      results: results,
      total_matches: results.reduce((sum, r) => sum + r.count, 0)
    }, null, 2), {
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({
      status: 'error',
      message: 'Search failed',
      error: error.message
    }, null, 2), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

// 获取术数书统计信息
async function getShushuStats(env: Env): Promise<Response> {
  try {
    const { Client } = await import('pg');
    const client = new Client({ 
      connectionString: env.HYPERDRIVE.connectionString 
    });
    
    await client.connect();
    
    const tableNames = ['shushu', 'shushu_book', 'books', 'articles', 'content', 'documents'];
    let stats: any[] = [];
    
    for (const tableName of tableNames) {
      try {
        const countResult = await client.query(`SELECT COUNT(*) as count FROM ${tableName}`);
        const sampleResult = await client.query(`SELECT * FROM ${tableName} LIMIT 1`);
        
        stats.push({
          table_name: tableName,
          record_count: parseInt(countResult.rows[0].count),
          sample_columns: sampleResult.rows.length > 0 ? Object.keys(sampleResult.rows[0]) : [],
          exists: true
        });
      } catch (e) {
        stats.push({
          table_name: tableName,
          exists: false
        });
      }
    }
    
    await client.end();
    
    return new Response(JSON.stringify({
      status: 'success',
      message: 'Statistics retrieved successfully',
      stats: stats,
      existing_tables: stats.filter(s => s.exists)
    }, null, 2), {
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({
      status: 'error',
      message: 'Failed to get statistics',
      error: error.message
    }, null, 2), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

async function testQuery(env: Env): Promise<Response> {
  try {
    const { Client } = await import('pg');
    const client = new Client({ 
      connectionString: env.HYPERDRIVE.connectionString 
    });
    
    await client.connect();
    
    // Create a test table if it doesn't exist
    await client.query(`
      CREATE TABLE IF NOT EXISTS hyperdrive_test (
        id SERIAL PRIMARY KEY,
        message TEXT,
        created_at TIMESTAMP DEFAULT NOW()
      )
    `);
    
    // Insert a test record
    const insertResult = await client.query(
      'INSERT INTO hyperdrive_test (message) VALUES ($1) RETURNING *',
      [`Test from Hyperdrive at ${new Date().toISOString()}`]
    );
    
    // Query recent records
    const selectResult = await client.query(
      'SELECT * FROM hyperdrive_test ORDER BY created_at DESC LIMIT 5'
    );
    
    await client.end();
    
    return new Response(JSON.stringify({
      status: 'success',
      message: 'Database operations completed successfully',
      inserted: insertResult.rows[0],
      recent_records: selectResult.rows,
      performance: {
        hyperdrive_enabled: true,
        connection_pooled: true
      }
    }, null, 2), {
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({
      status: 'error',
      message: 'Database query failed',
      error: error.message
    }, null, 2), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}