<?php
require __DIR__ . '/../vendor/autoload.php';
$app = require __DIR__ . '/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

use App\Models\Product;
use Illuminate\Support\Facades\DB;

echo "Scanning for duplicate products by name...\n";
$groups = DB::table('products')
    ->selectRaw('name, GROUP_CONCAT(id) as ids, COUNT(*) as cnt')
    ->groupBy('name')
    ->having('cnt', '>', 1)
    ->get();

if ($groups->isEmpty()) {
    echo "No duplicate products found.\n";
    exit;
}

$totalDeleted = 0;
foreach ($groups as $g) {
    $ids = explode(',', $g->ids);
    $keep = (int) array_shift($ids);
    echo "Processing '{$g->name}' -> keep id={$keep}, remove: " . implode(',', $ids) . "\n";

    // Move product_sizes (in sizes_db) to keep id
    try {
        $moved = DB::connection('sizes_db')->table('product_sizes')->whereIn('product_id', $ids)->update(['product_id' => $keep]);
        echo "  Moved product_sizes rows: {$moved}\n";
    } catch (\Exception $e) {
        echo "  Warning: could not update product_sizes on sizes_db: " . $e->getMessage() . "\n";
    }

    // Delete duplicates from products
    $deleted = DB::table('products')->whereIn('id', $ids)->delete();
    echo "  Deleted products: {$deleted}\n";
    $totalDeleted += $deleted;
}

echo "Done. Total deleted products: {$totalDeleted}\n";
