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

export async function POST(req: Request) {
  const logs: string[] = [];

  try {
    const creds = await req.json();

    const connection = await mysql.createConnection({
      host: creds.host,
      user: creds.user,
      password: creds.password,
      database: creds.database,
      connectTimeout: 15000,
    });

    const prefix = creds.prefix || "wp_";
    logs.push(`[INFO] Connected to MySQL. Prefix: ${prefix}`);

    // ── 1. Discover which post_types exist for courses ──────────────────────
    const [typeRows] = await connection.execute(`
      SELECT DISTINCT post_type, COUNT(*) as cnt 
      FROM ${prefix}posts 
      WHERE post_status = 'publish' 
      GROUP BY post_type 
      ORDER BY cnt DESC
    `);
    const allTypes = (typeRows as any[]).map((r) => `${r.post_type}(${r.cnt})`).join(", ");
    logs.push(`[INFO] Post types in DB: ${allTypes}`);

    // ── 2. Fetch published courses — broad match for any LMS / WC plugin ────
    const [rows] = await connection.execute(`
      SELECT ID, post_title, post_name, post_content, post_excerpt
      FROM ${prefix}posts 
      WHERE post_type IN (
        'product', 'course', 'courses', 'sfwd-courses', 'rima_course',
        'lesson', 'ld-courses', 'tutor_course', 'lp_course',
        'academist_course', 'academist_lesson', 'academist_quiz'
      ) 
      AND post_status = 'publish'
      ORDER BY ID ASC
    `);

    const products = rows as any[];
    logs.push(`[INFO] Found ${products.length} publishable courses/products`);

    let count = 0;
    const errors: string[] = [];

    for (const prod of products) {
      try {
        // ── 3. Find price from postmeta ──────────────────────────────────────
        const [metaRows] = await connection.execute(
          `SELECT meta_key, meta_value FROM ${prefix}postmeta 
           WHERE post_id = ? AND meta_key IN ('_regular_price', '_price', 'course_price', '_course_price')`,
          [prod.ID]
        );

        const meta = metaRows as any[];
        let price = 0;
        for (const m of meta) {
          if (m.meta_value && !isNaN(parseFloat(m.meta_value))) {
            price = parseFloat(m.meta_value);
            break;
          }
        }

        // ── 4. Build a safe slug ─────────────────────────────────────────────
        const rawSlug = prod.post_name || prod.post_title || `course-${prod.ID}`;
        const slug = rawSlug
          .toLowerCase()
          .replace(/[^a-z0-9-]/g, "-")
          .replace(/-+/g, "-")
          .slice(0, 200);

        const description =
          prod.post_excerpt ||
          (prod.post_content ? prod.post_content.substring(0, 500) : "Migrated from WordPress.");

        // ── 5. Upsert by wpPostId (most reliable unique key) ─────────────────
        await db.course.upsert({
          where: { wpPostId: prod.ID },
          update: {
            title: prod.post_title,
            slug: slug,
            description: description,
            price: price,
            isPublished: true,
          },
          create: {
            title: prod.post_title,
            slug: slug,
            description: description,
            price: price,
            isPublished: true,
            wpPostId: prod.ID,
          },
        });

        count++;
        logs.push(`[OK] Migrated: "${prod.post_title}" (ID: ${prod.ID}, slug: ${slug}, price: ${price})`);
      } catch (innerErr: any) {
        // If slug collision, try with ID suffix
        try {
          const fallbackSlug = `${(prod.post_name || "course").slice(0, 190)}-${prod.ID}`;
          const description =
            prod.post_excerpt ||
            (prod.post_content ? prod.post_content.substring(0, 500) : "Migrated from WordPress.");

          await db.course.upsert({
            where: { wpPostId: prod.ID },
            update: { title: prod.post_title, isPublished: true },
            create: {
              title: prod.post_title,
              slug: fallbackSlug,
              description: description,
              price: 0,
              isPublished: true,
              wpPostId: prod.ID,
            },
          });
          count++;
          logs.push(`[OK-FALLBACK] Migrated: "${prod.post_title}" with fallback slug`);
        } catch (e2: any) {
          errors.push(`[SKIP] ${prod.post_title} (ID: ${prod.ID}): ${e2.message}`);
        }
      }
    }

    await connection.end();

    return NextResponse.json({
      success: true,
      migrated: count,
      skipped: errors.length,
      logs: [...logs, ...errors],
    });
  } catch (error: any) {
    console.error("[MIGRATION_COURSES_ERROR]", error);
    return NextResponse.json(
      {
        error: `Eroare la migrarea cursurilor: ${error.message}`,
        logs,
      },
      { status: 500 }
    );
  }
}
