<?php

namespace App\Filament\Resources\ExpenseResource\Pages;

use App\Actions\Transactions\CreateTransactionAction;
use App\DataObjects\CreateTransactionDTO;
use App\Filament\Resources\ExpenseResource;
use Exception;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Pipeline;
use Symfony\Component\Console\Exception\LogicException;

class CreateExpense extends CreateRecord
{
    protected static string $resource = ExpenseResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {

        return $this->getFormDataMutation($data);
    }

    public function getFormDataMutation(array $data): array
    {
        return Arr::except($data, ['client', 'transactions']);
    }

    protected function afterCreate(): void
    {
        $transactions = $this->form->getState()['transactions'] ?? [];

        try {
            $branch = $this->getRecord()->branch;

            foreach ($transactions as $transaction) {

                $data = [
                    'branch_id' => $branch->id,
                    'happened_on' => $this->getRecord()->happened_on,
                    ...$transaction,
                ];

                $payload = new CreateTransactionDTO(data: $data, transactionable: $this->getRecord());

                Pipeline::send(passable: $payload)->through(
                    [
                        CreateTransactionAction::class,
                    ]
                )->thenReturn();
            }

            $this->commitDatabaseTransaction();
        } catch (Exception $exception) {
            $this->rollBackDatabaseTransaction();
            throw new LogicException('Failed to save transactions : '.$exception->getMessage());
        }
    }
}
