<?php

namespace Database\Seeders;

use App\Models\Catalog\MainCategory;
use App\Models\Catalog\SubCategory;
use App\Models\Central\Tenant;
use App\Services\CurrentContext;
use Illuminate\Database\Seeder;

/**
 * Idempotent seed of the application-owned catalog structure every tenant must
 * have: the protected "Packaging & Add-ons" main category, plus a starting set
 * of ordinary (freely editable, freely deletable) subcategories under it.
 *
 * Only the main category is system-owned. Nothing here creates products — a
 * packaging product is an ordinary product a tenant adds like any other, and
 * the POS simply hides the section while none exist.
 *
 * Runs per tenant, mirroring {@see LookupSeeder}: with a tenant bound it seeds
 * that one, otherwise it walks every tenant.
 */
class SystemCategorySeeder extends Seeder
{
    /** @var array<string, string> sort_code => name */
    public const PACKAGING_SUB_CATEGORIES = [
        'BAGS' => 'Shopping Bags',
        'GIFTBOX' => 'Gift Boxes',
        'GIFTPACK' => 'Gift Packing',
        'OTHR' => 'Other Add-ons',
    ];

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

        if ($context->hasTenant()) {
            $this->seedAll();

            return;
        }

        Tenant::all()->each(function (Tenant $tenant) use ($context): void {
            $context->runForTenant($tenant, fn () => $this->seedAll());
        });
    }

    private function seedAll(): void
    {
        $packaging = MainCategory::firstOrCreate(
            ['sort_code' => MainCategory::SYSTEM_PACKAGING],
            [
                'name' => MainCategory::SYSTEM_PACKAGING_NAME,
                'description' => 'Chargeable packaging and add-ons sold alongside a sale — bags, gift boxes, wrapping.',
                'is_active' => true,
                'is_system' => true,
            ],
        );

        // A tenant that already had this category from before it was system-owned.
        if (! $packaging->is_system) {
            $packaging->update(['is_system' => true]);
        }

        foreach (self::PACKAGING_SUB_CATEGORIES as $sortCode => $name) {
            SubCategory::firstOrCreate(
                ['main_category_id' => $packaging->id, 'sort_code' => $sortCode],
                ['name' => $name, 'is_active' => true],
            );
        }
    }
}
