<?php

namespace App\Console\Commands;

use App\Models\Sale;
use App\Support\SaleFulfillment;
use App\Support\SaleType;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SyncReturnedSaleTotalsCommand extends Command
{
    protected $signature = 'sales:sync-returned-totals';

    protected $description = 'Recalculate original sale amounts and product lines from active (non-returned) packs';

    public function handle(): int
    {
        $saleIds = Sale::query()
            ->where('type', SaleType::SALE)
            ->whereIn('id', Sale::query()
                ->where('type', SaleType::RETURN)
                ->whereNotNull('related_sale_id')
                ->select('related_sale_id'))
            ->orderBy('id')
            ->pluck('id');

        if ($saleIds->isEmpty()) {
            $this->info('No sales with returns found.');

            return self::SUCCESS;
        }

        $updated = 0;

        foreach ($saleIds as $saleId) {
            DB::transaction(function () use ($saleId, &$updated): void {
                $sale = Sale::query()->find($saleId);

                if ($sale === null) {
                    return;
                }

                SaleFulfillment::recalculateOriginalSaleFromActivePacks($sale);
                $updated++;
            });
        }

        $this->info("Recalculated {$updated} sale(s).");

        return self::SUCCESS;
    }
}
