import { NextResponse } from 'next/server';
import mysql from 'mysql2/promise';

const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'sitemente',
  password: process.env.DB_PASS || 'SiteMente2026!',
  database: process.env.DB_NAME || 'sitemente'
};

export async function GET() {
  let conn;
  try {
    conn = await mysql.createConnection(dbConfig);
    const [rows] = await conn.execute('SELECT * FROM research ORDER BY created_at DESC');
    return NextResponse.json(rows);
  } catch (e) {
    console.error(e);
    return NextResponse.json([]);
  } finally {
    if (conn) conn.end();
  }
}

export async function POST(request: Request) {
  let conn;
  try {
    const body = await request.json();
    conn = await mysql.createConnection(dbConfig);
    
    await conn.execute(
      'INSERT INTO research (name, query, results_count, summary, results, created_at) VALUES (?, ?, ?, ?, ?, NOW())',
      [body.name, body.query, body.results_count || 0, body.summary || '', JSON.stringify(body.results || [])]
    );
    
    const [rows] = await conn.execute('SELECT * FROM research ORDER BY created_at DESC');
    return NextResponse.json(rows);
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: 'Failed to save research' }, { status: 500 });
  } finally {
    if (conn) conn.end();
  }
}

export async function DELETE(request: Request) {
  let conn;
  try {
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');
    
    if (!id) return NextResponse.json({ error: 'Missing id' }, { status: 400 });
    
    conn = await mysql.createConnection(dbConfig);
    await conn.execute('DELETE FROM research WHERE id = ?', [id]);
    
    return NextResponse.json({ success: true });
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: 'Failed to delete' }, { status: 500 });
  } finally {
    if (conn) conn.end();
  }
}
