<?php

use App\Models\Central\Tenant;
use App\Models\Lookups\Status;
use App\Services\CurrentContext;
use Illuminate\Database\Migrations\Migration;

/**
 * Seed the `inactive` stock_batch status for existing tenants.
 *
 * Deactivation is the operator-driven counterpart to the automatic `expired`
 * sweep and the manual `recalled` flag: the lot is still physically on the
 * shelf and still counted in branch_stock, it is simply withheld from every
 * place lots are offered (POS, sales orders, transfers, adjustments,
 * write-offs). StockBatch::scopeActive() already filters on
 * code = 'active', so a lot parked here drops out of those lists for free.
 *
 * Statuses are per-tenant rows (Status uses BelongsToTenant), so this runs
 * inside a per-tenant sweep rather than inserting once. LookupSeeder carries
 * the same row (firstOrCreate) for fresh installs and provisioning.
 */
return new class extends Migration
{
    public function up(): void
    {
        $context = app(CurrentContext::class);

        foreach (Tenant::query()->get() as $tenant) {
            $context->runForTenant($tenant, function (): void {
                Status::query()->firstOrCreate(
                    ['context' => Status::CTX_STOCK_BATCH, 'code' => Status::BATCH_INACTIVE],
                    ['name' => 'Inactive', 'color' => 'gray', 'sort_order' => 25, 'is_active' => true],
                );
            });
        }
    }

    public function down(): void
    {
        $context = app(CurrentContext::class);

        foreach (Tenant::query()->get() as $tenant) {
            $context->runForTenant($tenant, function (): void {
                Status::query()
                    ->where('context', Status::CTX_STOCK_BATCH)
                    ->where('code', Status::BATCH_INACTIVE)
                    ->delete();
            });
        }
    }
};
