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

export async function POST(req: Request) {
  try {
    const creds = await req.json();
    
    const connection = await mysql.createConnection({
      host: creds.host,
      user: creds.user,
      password: creds.password,
      database: creds.database,
    });

    const prefix = creds.prefix || "wp_";

    const [courses] = await connection.execute(`SELECT COUNT(*) as count FROM ${prefix}posts WHERE post_type = 'product' OR post_type = 'course'`);
    const [users] = await connection.execute(`SELECT COUNT(*) as count FROM ${prefix}users`);

    await connection.end();

    const courseCount = (courses as any)[0].count;
    const userCount = (users as any)[0].count;

    return NextResponse.json({ success: true, counts: { courses: courseCount, users: userCount } });
  } catch (error: any) {
    console.error("[MIGRATION_CONNECT_ERROR]", error);
    return NextResponse.json({ error: "Eroare conectare: Verifica datele MySQL" }, { status: 500 });
  }
}
