<?php

namespace App\Filament\Resources\ProductResource\Pages;

use App\Filament\Resources\ProductResource;
use App\Filament\Support\Perm;
use App\Models\Catalog\Product;
use App\Services\AuditLog;
use Filament\Actions\CreateAction;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Filament\Support\Enums\Width;

class ListProducts extends ListRecords
{
    protected static string $resource = ProductResource::class;

    protected Width|string|null $maxContentWidth = Width::Full;

    protected function getHeaderActions(): array
    {
        return [
            CreateAction::make(),
        ];
    }

    public function toggleProductTracking(
        int $productId,
        string $field
    ): void {
        /*
         * Changing these settings is a product edit, so use the same
         * permission as the normal Product Edit page.
         */
        abort_unless(
            Perm::can('isms_products', 'edit'),
            403
        );

        $allowedFields = [
            'is_batch_tracked',
            'is_serial_tracked',
            'is_expiry_tracked',
        ];

        abort_unless(
            in_array($field, $allowedFields, true),
            422
        );

        /** @var Product|null $product */
        $product = ProductResource::getEloquentQuery()
            ->whereKey($productId)
            ->first();

        abort_unless($product, 404);

        $oldValue = (bool) $product->{$field};
        $newValue = ! $oldValue;

        /*
         * Expiry tracking only makes sense for batch-tracked products.
         *
         * This matches the exact rule already enforced by the Product
         * create/edit forms.
         */
        if ($field === 'is_expiry_tracked' && ! $product->is_batch_tracked) {
            Notification::make()
                ->title('Expiry tracking requires batch tracking')
                ->body('Enable Batch Tracking first.')
                ->warning()
                ->send();

            return;
        }

        /*
         * Turning Batch Tracking OFF must also turn Expiry Tracking OFF.
         *
         * This matches ProductResource::form() and EditProduct.
         */
        if ($field === 'is_batch_tracked' && ! $newValue) {
            $product->is_batch_tracked = false;
            $product->is_expiry_tracked = false;

            $product->save();

            AuditLog::record('product.updated', $product, [
                'name' => $product->name,
                'code' => $product->sku,
                'changed' => [
                    'is_batch_tracked',
                    'is_expiry_tracked',
                ],
                'changes' => [
                    'is_batch_tracked' => [
                        'from' => $oldValue,
                        'to' => false,
                    ],
                    'is_expiry_tracked' => [
                        'from' => true,
                        'to' => false,
                    ],
                ],
            ]);

            Notification::make()
                ->title('Batch tracking disabled')
                ->body('Expiry tracking was also disabled.')
                ->success()
                ->send();

            return;
        }

        $product->{$field} = $newValue;
        $product->save();

        AuditLog::record('product.updated', $product, [
            'name' => $product->name,
            'code' => $product->sku,
            'changed' => [$field],
            'changes' => [
                $field => [
                    'from' => $oldValue,
                    'to' => $newValue,
                ],
            ],
        ]);

        $labels = [
            'is_batch_tracked' => 'Batch tracking',
            'is_serial_tracked' => 'Serial tracking',
            'is_expiry_tracked' => 'Expiry tracking',
        ];

        Notification::make()
            ->title(
                ($labels[$field] ?? 'Product setting')
                . ($newValue ? ' enabled' : ' disabled')
            )
            ->success()
            ->send();
    }
}