<?php

namespace App\Console\Commands;

use App\Models\StationPrice;
use App\Models\StationPriceArchive;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class ArchiveOldPricesCommand extends Command
{
    protected $signature = 'fuel:archive';

    protected $description = 'Move station price history older than 12 months to the archive table';

    public function handle(): int
    {
        $cutoff = Carbon::now()->subMonths(12);

        $count = StationPrice::where('price_effective_at', '<', $cutoff)->count();

        if ($count === 0) {
            $this->info('No prices to archive.');

            return self::SUCCESS;
        }

        $this->info("Archiving {$count} price record(s) older than {$cutoff->toDateString()}...");

        StationPrice::where('price_effective_at', '<', $cutoff)
            ->chunkById(1000, function ($prices): void {
                $rows = $prices->map(fn (StationPrice $price): array => [
                    'station_id' => $price->station_id,
                    'fuel_type' => $price->fuel_type->value,
                    'price_pence' => $price->price_pence,
                    'price_effective_at' => $price->price_effective_at,
                    'price_reported_at' => $price->price_reported_at,
                    'recorded_at' => $price->recorded_at,
                ])->all();

                DB::transaction(function () use ($rows, $prices): void {
                    StationPriceArchive::insert($rows);
                    StationPrice::whereIn('id', $prices->pluck('id'))->delete();
                });
            });

        $this->info('Archive complete.');

        return self::SUCCESS;
    }
}
