<?php

namespace App\Filament\Resources\Sales\Pages;

use Filament\Actions\DeleteAction;
use Exception;
use App\Actions\Transactions\CreateTransactionAction;
use App\DataObjects\CreateTransactionDTO;
use App\Filament\Resources\Sales\SaleResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Pipeline;

class EditSale extends EditRecord
{
    protected static string $resource = SaleResource::class;

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

    protected function mutateFormDataBeforeSave(array $data): array
    {
        return $this->getFormDataMutation($data);
    }

    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        $transactions = $this->data['transactions'] ?? [];
        return $this->processUpdate($record, $data, $transactions);
    }

    public function getFormDataMutation(array $data): array
    {
        $transactions = $data['transactions'] ?? [];

        $data['gross_amount'] = collect($transactions)->sum(fn (array $transaction) => (float) ($transaction['gross_amount'] ?? 0));
        $data['exempt'] = collect($transactions)->sum(fn (array $transaction) => (float) ($transaction['exempt'] ?? 0));
        $data['vatable_amount'] = collect($transactions)->sum(fn (array $transaction) => (float) ($transaction['vatable_amount'] ?? 0));
        $data['output_tax'] = collect($transactions)->sum(fn (array $transaction) => (float) ($transaction['output_tax'] ?? 0));
        $data['payable_withholding_tax'] = collect($transactions)->sum(fn (array $transaction) => (float) ($transaction['payable_withholding_tax'] ?? 0));
        $data['discount'] = collect($transactions)->sum(fn (array $transaction) => (float) ($transaction['discount'] ?? 0));
        $data['net_amount'] = collect($transactions)->sum(fn (array $transaction) => (float) ($transaction['net_amount'] ?? 0));

        return Arr::except($data, ['client', 'transactions', 'with_discount']);
    }

    public function processUpdate(Model $record, array $data, array $transactions): Model
    {
        try {
            DB::beginTransaction();
            $record->update($data);
            $branch = $record->branch;

            // Delete existing transactions and their related ledgers/balances
            $record->transactions->each(function ($transaction) {
                $transaction->ledgers->each(function ($ledger) {
                    $ledger->balances()->delete();
                    $ledger->delete();
                });
                $transaction->delete();
            });

            // Create new transactions
            foreach ($transactions as $transaction) {
                $tData = [
                    'branch_id' => $branch->id,
                    'happened_on' => $record->happened_on,
                    ...$transaction,
                ];

                $payload = new CreateTransactionDTO(data: $tData, transactionable: $record);

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

            $accountIds = collect($transactions)
                ->pluck('account_id')
                ->filter()
                ->unique()
                ->values()
                ->all();

            $record->accounts()->sync($accountIds);

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            throw new Exception('Failed to save transactions : '.$exception->getMessage());
        }

        return $record;
    }
}
