<?php

namespace App\Filament\Resources\StockAdjustmentResource\Pages;

use App\Exceptions\InsufficientStockException;
use App\Filament\Resources\Concerns\ReportsStockShortfall;
use App\Filament\Resources\StockAdjustmentResource;
use App\Models\Inventory\StockAdjustment;
use App\Services\AuditLog;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;

class CreateStockAdjustment extends CreateRecord
{
    use ReportsStockShortfall;

    protected static string $resource = StockAdjustmentResource::class;

    protected function handleRecordCreation(array $data): StockAdjustment
    {
        StockAdjustmentResource::assertBranchAccessible((int) $data['branch_id']);

        try {
            $adjustment = StockAdjustmentResource::apply($data);
        } catch (InsufficientStockException $e) {
            // Correcting a lot downwards moves the branch total by the same
            // amount, so a branch whose total has drifted below its lots can
            // still refuse the write. Report it on the figure being entered.
            throw static::stockShortfall($e, 'data.new_stock');
        } catch (InvalidArgumentException $e) {
            throw ValidationException::withMessages([
                'data.stock_batch_id' => $e->getMessage(),
            ]);
        }

        AuditLog::record('stock_adjustment.created', $adjustment, [
            'branch' => $adjustment->branch?->name,
            'product' => $adjustment->product?->name,
            'reason' => $adjustment->reason?->name,
            'before_stock' => $adjustment->before_stock,
            'new_stock' => $adjustment->new_stock,
            'diff' => $adjustment->diff,
            'note' => $adjustment->note,
        ]);

        return $adjustment;
    }
}
