<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Enums\CashTransactionType;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Finance\CashTransactionRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\CashTransaction;
use App\Services\Admin\Finance\CashAccountService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class CashAccountController extends Controller
{
    public function __construct(
        private readonly CashAccountService $service
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        $cashAccount = $this->service->get();

        return Inertia::render('admin/finance/cash-account/index', [
            'cashAccount' => $cashAccount,
            'transactions' => $this->service->paginatedTransactions(
                ...$request->validatedWithDefaults(),
                filters: $request->only(['type']),
            ),
            'filters' => $request->only(['type']),
            'filterOptions' => [
                'typeOptions' => CashTransactionType::toSelect(),
            ],
        ]);
    }

    public function deposit(CashTransactionRequest $request): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->deposit($request->validated()),
            'Deposit berhasil ditambahkan.',
            'admin.finance.cash-accounts.index'
        );
    }

    public function withdrawal(CashTransactionRequest $request): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->withdrawal($request->validated()),
            'Withdrawal berhasil ditambahkan.',
            'admin.finance.cash-accounts.index'
        );
    }

    public function update(CashTransactionRequest $request, CashTransaction $transaction): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->updateTransaction($transaction, $request->validated()),
            'Transaksi berhasil diperbarui.',
            'admin.finance.cash-accounts.index'
        );
    }

    public function destroy(CashTransaction $transaction): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->deleteTransaction($transaction),
            'Transaksi berhasil dihapus.',
            'admin.finance.cash-accounts.index'
        );
    }
}
