<?php

namespace Database\Seeders;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Review;
use App\Models\SubCategory;
use App\Models\Category;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class ProductReviewSeeder extends Seeder
{
    public function run(): void
    {
        // Ensure there are enough categories and subcategories
        if (Category::count() === 0 || SubCategory::count() === 0) {
            $this->call(CatalogSeeder::class);
        }

        // Ensure at least 100 products exist
        $productCount = Product::count();
        if ($productCount < 100) {
            $need = 100 - $productCount;
            $cats = Category::pluck('id')->all();
            $subs = SubCategory::pluck('id')->all();
            for ($i = 0; $i < $need; $i++) {
                $cid = $cats[array_rand($cats)];
                $sid = $subs[array_rand($subs)];
                $name = fake()->unique()->words(3, true);
                Product::create([
                    'category_id' => $cid,
                    'sub_category_id' => $sid,
                    'name' => ucfirst($name),
                    'slug' => Str::slug($name) . '-' . Str::random(6),
                    'description' => fake()->sentence(12),
                    'price' => fake()->randomFloat(2, 20, 1200),
                    'discount_price' => fake()->boolean(30) ? fake()->randomFloat(2, 15, 1100) : null,
                    'stock' => fake()->numberBetween(10, 300),
                    'unit' => fake()->randomElement(['kg', 'g', 'L', 'ml', 'pcs', 'pack']),
                    'image' => 'https://placehold.co/600x400?text=Product',
                    'images' => null,
                    'is_active' => true,
                    'is_featured' => fake()->boolean(15),
                    'is_special_offer' => fake()->boolean(10),
                    'is_premium' => fake()->boolean(5),
                ]);
            }
        }

        // Prepare a pool of users to author reviews
        $userPool = User::inRandomOrder()->limit(30)->get();
        if ($userPool->count() < 30) {
            $more = 30 - $userPool->count();
            User::factory($more)->create();
            $userPool = User::inRandomOrder()->limit(30)->get();
        }

        $comments = [
            'Excellent quality and super fresh.',
            'Packaging was great and delivery on time.',
            'Value for money. Highly recommended.',
            'Taste and texture are perfect.',
            'Consistent quality—ordering again.',
            'Great product, exceeded expectations.',
            'Premium quality just as described.',
            'Loved it! Will buy again.',
            'Fantastic freshness and flavor.',
            'Quality was top-notch—fast delivery too.',
        ];

        // For each product, create 5 delivered orders and reviews
        Product::query()->chunk(50, function ($products) use ($userPool, $comments) {
            foreach ($products as $product) {
                // Avoid duplicating reviews if already seeded
                $existing = Review::where('product_id', $product->id)->count();
                $toCreate = max(0, 5 - $existing);
                if ($toCreate === 0) {
                    continue;
                }
                for ($i = 0; $i < $toCreate; $i++) {
                    $user = $userPool->random();
                    $qty = rand(1, 3);
                    $unitPrice = (float) ($product->discount_price ?? $product->price ?? 0);
                    if ($unitPrice <= 0) {
                        $unitPrice = (float) rand(20, 1200);
                    }
                    $subtotal = $unitPrice * $qty;

                    $order = Order::create([
                        'user_id' => $user->id,
                        'order_number' => 'ORD-' . strtoupper(Str::random(10)),
                        'subtotal' => $subtotal,
                        'delivery_fee' => 0,
                        'tax' => 0,
                        'discount' => 0,
                        'total' => $subtotal,
                        'status' => 'delivered',
                        'payment_status' => 'paid',
                        'shipping_address' => ['city' => 'Dhaka', 'country' => 'Bangladesh'],
                        'billing_address' => ['city' => 'Dhaka', 'country' => 'Bangladesh'],
                        'notes' => null,
                    ]);

                    $orderItem = OrderItem::create([
                        'order_id' => $order->id,
                        'product_id' => $product->id,
                        'quantity' => $qty,
                        'price' => $unitPrice,
                        'total' => $subtotal,
                    ]);

                    Review::create([
                        'user_id' => $user->id,
                        'product_id' => $product->id,
                        'order_item_id' => $orderItem->id,
                        'rating' => rand(4, 5),
                        'comment' => $comments[array_rand($comments)],
                    ]);
                }
            }
        });
    }
}

