<?php

namespace App\Console\Commands;

use App\Services\Sales\ProductSalesQuantityService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class AuditProductSalesQuantity extends Command
{
    protected $signature = 'sales:audit-quantity {product_id?} {--all} {--backfill}';
    protected $description = 'Audit product sold quantities by stable product id; optionally refresh the display cache';

    public function handle(ProductSalesQuantityService $sales): int
    {
        $ids = $this->option('all')
            ? DB::table('items')->orderBy('id')->pluck('id')->map(fn ($id) => (int) $id)->all()
            : [(int) $this->argument('product_id')];
        $ids = array_values(array_filter($ids));
        if ($ids === []) {
            $this->error('Pass product_id or --all.');
            return self::INVALID;
        }

        $quantities = $sales->quantities($ids);
        $this->table(['Product ID', 'Net Sold'], collect($ids)->map(fn ($id) => [$id, $quantities[$id] ?? 0]));

        if ($this->option('backfill')) {
            if (! Schema::hasColumn('items', 'order_count')) {
                $this->warn('items.order_count does not exist; no cache was written.');
                return self::SUCCESS;
            }
            DB::transaction(function () use ($quantities) {
                foreach ($quantities as $id => $quantity) {
                    DB::table('items')->where('id', $id)->update(['order_count' => $quantity]);
                }
            });
            $this->info('Display cache refreshed; sales, stock, and accounting rows were not modified.');
        }

        if (count($ids) === 1) {
            $this->line(json_encode($sales->audit($ids[0]), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        }
        return self::SUCCESS;
    }
}
