<?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\Cash\CashAccountService;
use App\Services\Admin\Finance\Cash\CashTransactionService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class CashAccountController extends Controller
{
    public function __construct(
        private CashAccountService $cashAccountService,
        private CashTransactionService $cashTransactionService,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/finance/cash-account/index', [
            'cashAccount' => $this->cashAccountService->get(),
            'transactions' => $this->cashTransactionService->paginated(
                ...$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->cashTransactionService->deposit($request->validated()),
            'Deposit berhasil ditambahkan.',
            'admin.finance.cash-accounts.index'
        );
    }

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

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

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