<?php

namespace App\Filament\Resources\ProductBundleResource\Pages;

use App\Filament\Resources\ProductBundleResource;
use App\Models\Catalog\ProductBundle;
use App\Services\AuditLog;
use Filament\Resources\Pages\CreateRecord;

class CreateProductBundle extends CreateRecord
{
    protected static string $resource = ProductBundleResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        if (filled($data['branch_id'] ?? null)) {
            ProductBundleResource::assertBranchAccessible((int) $data['branch_id']);
        }

        if (blank($data['sku'] ?? null)) {
            $data['sku'] = ProductBundleResource::generateSku();
        }

        return $data;
    }

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

        AuditLog::record('product_bundle.created', $bundle, ['name' => $bundle->name]);
    }
}
