<?php

namespace App\Filament\Resources\ProductResource\Pages;

use App\Filament\Resources\ProductResource;
use App\Models\Catalog\MainCategory;
use App\Models\Catalog\Product;
use App\Models\Catalog\SubCategory;
use App\Services\AuditLog;
use App\Services\VatSettings;
use App\Support\ProductAttributeSync;
use Filament\Resources\Pages\CreateRecord;

class CreateProduct extends CreateRecord
{
    protected static string $resource = ProductResource::class;

    /**
     * @var array<int, array{key?: string, value?: string|null}>
     */
    protected array $pendingAttributes = [];

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $this->pendingAttributes = array_values($data['attributes'] ?? []);
        unset($data['attributes']);

        // The upload control is not the column — one shared place turns it into
        // an `image_url` path (see ProductResource::applyImageInput()).
        $data = ProductResource::applyImageInput($data);

        $main = MainCategory::find($data['main_category_id']);
        $sub = ! empty($data['sub_category_id']) ? SubCategory::with('mainCategory')->find($data['sub_category_id']) : null;

        $data['sku'] = ProductResource::generateSku($sub, $main);

        // Every product gets a scannable barcode. Blank = auto-generated from
        // the SKU, so edits that clear the field silently fall back too.
        $data['barcode'] ??= $data['sku'];

        // The form field is hidden while VAT is off, but a hidden field can
        // still dehydrate a stale value — force it back to 0 server-side too.
        if (! app(VatSettings::class)->enabled()) {
            $data['vat_rate'] = 0;
        }

        // Expiry tracking only applies to batch-tracked products.
        if (empty($data['is_batch_tracked'])) {
            $data['is_expiry_tracked'] = false;
        }

        return $data;
    }

    protected function afterCreate(): void
    {
        /** @var Product $product */
        $product = $this->record;

        ProductAttributeSync::apply($product, $this->pendingAttributes);

        AuditLog::record('product.created', $product, [
            'name' => $product->name,
            'code' => $product->sku,
        ]);
    }
}
