<?php

namespace Database\Seeders;

use App\Models\Product;
use Illuminate\Database\Seeder;

class ProductDistributeSeeder extends Seeder
{
    /**
     * Distribute existing products across different categories.
     *
     * This seeder takes all products currently assigned to category 9
     * and redistributes them across all parent categories.
     */
    public function run(): void
    {
        $parentCategories = \App\Models\Category::whereNull('parent_id')->get();

        if ($parentCategories->isEmpty()) {
            $this->command->warn('No parent categories found.');

            return;
        }

        $products = Product::all();

        if ($products->isEmpty()) {
            $this->command->warn('No products found to distribute.');

            return;
        }

        $this->command->info("Found {$products->count()} products to distribute.");
        $this->command->info("Found {$parentCategories->count()} parent categories.");

        // Distribute products evenly across categories
        $productsPerCategory = ceil($products->count() / $parentCategories->count());
        $productChunks = $products->chunk($productsPerCategory);

        $categoryIndex = 0;
        $totalUpdated = 0;

        foreach ($parentCategories as $category) {
            if (! isset($productChunks[$categoryIndex])) {
                break;
            }

            $chunk = $productChunks[$categoryIndex];
            $updatedCount = 0;

            foreach ($chunk as $product) {
                $product->category_id = $category->id;
                $product->save();
                $updatedCount++;
            }

            $this->command->info("✓ Assigned {$updatedCount} products to {$category->name_en} (ID: {$category->id})");
            $totalUpdated += $updatedCount;
            $categoryIndex++;
        }

        $this->command->info("✅ Successfully distributed {$totalUpdated} products across categories.");
    }
}
