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

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_";

    // Fetch users
    const [rows] = await connection.execute(`
      SELECT ID, user_login, user_email, user_pass, display_name 
      FROM ${prefix}users 
    `);

    const wpUsers = rows as any[];
    let count = 0;

    for (const wu of wpUsers) {
      if (!wu.user_email) continue;
      
      // We don't port WordPress passwords directly since the hashing algorithm differs.
      // We will create a dummy password hash (users will have to reset password)
      // or we just assign a random string, they can use 'Forgot Password'.
      // Better yet, WooCommerce customer role is what we care about mostly.
      
      const [metaRows] = await connection.execute(`
        SELECT meta_key, meta_value FROM ${prefix}usermeta 
        WHERE user_id = ? AND meta_key IN ('first_name', 'last_name', 'billing_company', 'billing_cui')
      `, [wu.ID]);
      
      const meta = metaRows as any[];
      const getMeta = (key: string) => meta.find(m => m.meta_key === key)?.meta_value || "";

      const firstName = getMeta("first_name") || wu.display_name || "Utilizator";
      const lastName = getMeta("last_name") || "";
      const companyName = getMeta("billing_company");
      const cui = getMeta("billing_cui");

      let companyId = null;
      if (companyName && cui) {
        // Create or find company
        const company = await db.company.upsert({
          where: { cui },
          update: {},
          create: { name: companyName, cui, regCom: "", address: "" }
        });
        companyId = company.id;
      }

      await db.user.upsert({
        where: { email: wu.user_email },
        update: {},
        create: {
          email: wu.user_email,
          passwordHash: wu.user_pass, // WP Hash - will be invalid for bcrypt, so user will be forced to reset if they try to login
          firstName,
          lastName,
          companyId,
          role: "STUDENT"
        }
      });
      count++;
    }

    await connection.end();

    return NextResponse.json({ success: true, migrated: count });
  } catch (error: any) {
    console.error("[MIGRATION_USERS_ERROR]", error);
    return NextResponse.json({ error: "Eroare la migrarea utilizatorilor." }, { status: 500 });
  }
}
