<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Asset;
use App\Models\AssetHistory;
use Carbon\Carbon;

class LastStatusUpdateSync extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'LastStatusUpdateSync:sync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'One time runnable commands for quick fixes / updates on existing data';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $allAssets = Asset::select('id', 'last_status_update')->whereHas('assetHistory')->get();

        foreach ($allAssets as $asset) {

            $latestUpdateHistory = AssetHistory::select('updated_at')->where('asset_id', $asset->id)->whereIn('action', ['created', 'status_updated'])->latest()->first();

            if ($latestUpdateHistory !== null) {
                $asset->update(['last_status_update' => $latestUpdateHistory->getRawOriginal('updated_at')]);
            }
        }

        $this->info("Last status update date added for all assets");
    }
}
