<?php
// database/seeders/ReviewsSeeder.php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Review;
use App\Models\Order;
use App\Models\OrderItem;

class ReviewsSeeder extends Seeder
{
    public function run(): void
    {
        // Create reviews from order items that have ratings
        $orderItemsWithRatings = OrderItem::whereNotNull('rating')->get();
        
        foreach ($orderItemsWithRatings as $item) {
            Review::create([
                'order_id' => $item->order_id,
                'customer_id' => $item->order->customer_id,
                'menu_id' => $item->menu_id,
                'rating' => $item->rating,
                'comment' => $item->review_comment,
                'is_approved' => rand(0, 10) > 1, // 90% approved
                'created_at' => $item->reviewed_at ?? $item->created_at,
                'updated_at' => now(),
            ]);
        }
        
        // Create some additional reviews
        $completedOrders = Order::where('status', 'completed')
            ->whereHas('customer')
            ->whereHas('orderItems.menu')
            ->get();
        
        foreach ($completedOrders->take(20) as $order) {
            $menu = $order->orderItems->first()->menu;
            
            if (!Review::where('order_id', $order->id)->where('menu_id', $menu->id)->exists()) {
                Review::factory()->create([
                    'order_id' => $order->id,
                    'customer_id' => $order->customer_id,
                    'menu_id' => $menu->id,
                ]);
            }
        }
        
        // Create some unapproved reviews
        Review::factory()
            ->count(5)
            ->state(['is_approved' => false])
            ->create();
        
        $this->command->info('✅ Reviews seeded! Total: ' . Review::count());
    }
}