<?php

namespace App\Filament\Resources\TransferenciaBodegaResource\Pages;

use App\Filament\Resources\TransferenciaBodegaResource;
use App\Services\TransferenciaBodegaService;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
use Filament\Notifications\Notification;

class CreateTransferenciaBodega extends CreateRecord
{
    protected static string $resource = TransferenciaBodegaResource::class;

    protected function handleRecordCreation(array $data): \Illuminate\Database\Eloquent\Model
    {
        $transferenciaBodegaService = app(TransferenciaBodegaService::class);
        
        try {
            if (!empty($data['variante_id'])) {
                // Transferencia de variante
                $transferencia = $transferenciaBodegaService->transferirVariante(
                    $data['variante_id'],
                    $data['bodega_origen_id'],
                    $data['bodega_destino_id'],
                    $data['cantidad'],
                    $data['motivo'] ?? null
                );
            } else {
                // Transferencia de producto
                $transferencia = $transferenciaBodegaService->transferir(
                    $data['producto_id'],
                    $data['bodega_origen_id'],
                    $data['bodega_destino_id'],
                    $data['cantidad'],
                    $data['motivo'] ?? null
                );
            }

            Notification::make()
                ->title('Transferencia completada exitosamente')
                ->success()
                ->send();

            return $transferencia;
            
        } catch (\Exception $e) {
            Notification::make()
                ->title('Error en la transferencia')
                ->body($e->getMessage())
                ->danger()
                ->send();
            
            throw $e;
        }
    }
}
