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

// 创建全局的 MySQL 连接池
const pool = mysql.createPool({
  connectionLimit: 100,
  host: '60.204.184.98', // 服务器地址
  port: 33308,
  user: 'chat',
  password: 'DZzx6ACMhinTtTtS', // 密码
  database: 'chat',
})

interface Request {
  id: string;
  messages: {
    id: string;
    date: string;
    role: "system" | "user" | "assistant";
    content: string;
  }[];
}

export async function POST(req: any) {
  try {
    // 从连接池中获取连接
    const connection = await pool.getConnection()
    const data: Request = await req.json();
    const id = data.id;
    const messages = data.messages;

    const [rows, fields] = await connection.query('SELECT * FROM dialog where id = ?', [id]);

    if ((rows as any).length === 0) {
      // 执行 MySQL 添加头表
      await connection.execute('INSERT INTO dialog (id, create_time) VALUES (?,?)', [id, new Date])
    }

    messages.forEach(async function (message) {
      const detailId = message.id;
      const role = message.role;
      const createDate = message.date;
      const content = message.content;
      const [detailRows, fields] = await connection.query('SELECT * FROM dialog_detail where id = ?', [detailId]);
      if ((detailRows as any).length === 0) {
        // 执行 MySQL 添加明细表
        await connection.execute('INSERT INTO dialog_detail (id,dialog_id,type,content,create_by, create_time) VALUES (?, ?, ?,?,?,?)', [detailId, id, role, content, role, createDate])
      }
    });

    // 释放连接回连接池
    connection.release()
    return NextResponse.json({ message: 'ok', data: (rows as any).length }, { status: 200 })
  } catch (error) {
    console.error('Error:', error)
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  }
}

export async function GET() {
  try {
    // 从连接池中获取连接
    const connection = await pool.getConnection()

    // 执行 MySQL 查询
    const [rows, fields] = await connection.query('SELECT he.id,he.dialog_name,de.id did,de.dialog_id,de.type,de.content,de.create_time ' +
        'FROM dialog he left join dialog_detail de on he.id = de.dialog_id order by he.create_time desc, he.id , de.create_time, type desc')

    // 释放连接回连接池
    connection.release()

    return NextResponse.json({ data: rows }, { status: 200 })
  } catch (error) {
    console.error('Error:', error)
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  }
}