<?php

namespace App\Console\Commands;

use App\Models\Part;
use App\Models\PartHistory;
use App\Models\StockMovement;
use Illuminate\Console\Command;

class GeneratePartHistory extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'part:generate-history {--part_id=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate sample part history for testing';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $partId = $this->option('part_id');
        
        if ($partId) {
            $parts = Part::where('id', $partId)->get();
        } else {
            $parts = Part::take(5)->get();
        }

        if ($parts->isEmpty()) {
            $this->error('No parts found');
            return;
        }

        foreach ($parts as $part) {
            $this->info("Generating history for part: {$part->name}");
            
            // Generate creation history
            PartHistory::create([
                'part_id' => $part->id,
                'event_type' => PartHistory::EVENT_CREATED,
                'new_values' => [
                    'name' => $part->name,
                    'part_number' => $part->part_number,
                    'cost_price' => $part->cost_price,
                    'sell_price' => $part->sell_price,
                ],
                'notes' => 'Part initially created',
                'ip_address' => '127.0.0.1',
                'user_agent' => 'Console Command',
                'created_by' => 1,
                'created_at' => $part->created_at,
                'updated_at' => $part->created_at,
            ]);

            // Generate some stock movements
            $movements = [
                ['type' => 'in', 'qty' => 50, 'note' => 'Initial stock'],
                ['type' => 'in', 'qty' => 25, 'note' => 'Restocked inventory'],
                ['type' => 'out', 'qty' => 10, 'note' => 'Used in service'],
                ['type' => 'adjustment', 'qty' => -2, 'note' => 'Inventory correction'],
            ];

            $currentStock = $part->quantity_on_hand;
            $runningTotal = 0;

            foreach ($movements as $index => $movement) {
                // Create dates that span from a week ago to today to ensure some records show up
                $daysAgo = max(0, 7 - $index); // This will create records from 7 days ago to today
                $createdAt = now()->subDays($daysAgo)->subHours(rand(1, 12));
                
                $quantityBefore = $runningTotal;
                $quantityChange = $movement['type'] === 'out' ? -$movement['qty'] : $movement['qty'];
                $quantityAfter = $quantityBefore + $quantityChange;
                $runningTotal = $quantityAfter;

                PartHistory::create([
                    'part_id' => $part->id,
                    'event_type' => $movement['type'] === 'in' ? PartHistory::EVENT_STOCK_IN : 
                                  ($movement['type'] === 'out' ? PartHistory::EVENT_STOCK_OUT : PartHistory::EVENT_ADJUSTMENT),
                    'quantity_change' => $quantityChange,
                    'quantity_before' => $quantityBefore,
                    'quantity_after' => $quantityAfter,
                    'reference_type' => 'manual_adjustment',
                    'notes' => $movement['note'],
                    'ip_address' => '127.0.0.1',
                    'user_agent' => 'Console Command',
                    'created_by' => 1,
                    'created_at' => $createdAt,
                    'updated_at' => $createdAt,
                ]);
            }

            // Generate price change
            $oldPrice = $part->cost_price;
            $newPrice = $oldPrice * 1.1; // 10% increase

            PartHistory::create([
                'part_id' => $part->id,
                'event_type' => PartHistory::EVENT_PRICE_CHANGE,
                'old_values' => ['cost_price' => $oldPrice],
                'new_values' => ['cost_price' => $newPrice],
                'cost_before' => $oldPrice,
                'cost_after' => $newPrice,
                'notes' => 'Price updated due to supplier cost increase',
                'ip_address' => '127.0.0.1',
                'user_agent' => 'Console Command',
                'created_by' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            $this->info("✓ Generated " . PartHistory::where('part_id', $part->id)->count() . " history records for {$part->name}");
        }

        $totalHistory = PartHistory::count();
        $this->info("\nTotal part history records in database: {$totalHistory}");
    }
}
