<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Order;
use App\Models\OrderStatusHistory;
use App\Models\User;

class OrderStatusHistorySeeder extends Seeder
{
    public function run()
    {
        $this->command->info('Creating order status histories...');
        
        $orders = Order::all();
        $admins = User::role(['super-admin', 'admin', 'manager'])->get();
        $statuses = ['pending', 'accepted', 'preparing', 'ready', 'picked_up', 'delivered'];
        
        foreach ($orders as $order) {
            $currentStatusIndex = array_search($order->status, $statuses);
            
            // Create history for status progression
            for ($i = 0; $i <= $currentStatusIndex; $i++) {
                $admin = $admins->random();
                
                OrderStatusHistory::create([
                    'order_id' => $order->id,
                    'old_status' => $i > 0 ? $statuses[$i - 1] : null,
                    'new_status' => $statuses[$i],
                    'changed_by_role' => $admin->getRoleNames()->first(),
                    'changed_by_id' => $admin->id,
                    'reason' => $i === 0 ? 'Order placed' : 'Status updated',
                    'created_at' => $order->created_at->addMinutes($i * 15),
                    'updated_at' => $order->created_at->addMinutes($i * 15)
                ]);
            }
        }
        
        $this->command->info('Order status histories created successfully!');
    }
}