<?php

namespace Modules\Finance\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Modules\Finance\Clients\FinanceModuleClient;
use Modules\Finance\ViewModels\CategoryView;

class IncomeCategoryController extends Controller
{
    public function __construct(
        private readonly FinanceModuleClient $finance,
    ) {}

    public function index(Request $request): View
    {
        $this->authorize('finance.categories.manage');

        return view('finance::categories.income-index', [
            'categories' => $this->finance->paginateIncomeCategories($request->only('search')),
        ]);
    }

    public function create(): View
    {
        $this->authorize('finance.categories.manage');

        return view('finance::categories.income-create');
    }

    public function store(Request $request): RedirectResponse
    {
        $this->authorize('finance.categories.manage');

        $this->finance->createIncomeCategory($this->validated($request));

        return redirect()
            ->route('finance.income-categories.index')
            ->with('status', 'Income category created.');
    }

    public function edit(CategoryView $category): View
    {
        $this->authorize('finance.categories.manage');

        return view('finance::categories.income-edit', [
            'category' => $category,
        ]);
    }

    public function update(Request $request, CategoryView $category): RedirectResponse
    {
        $this->authorize('finance.categories.manage');

        $this->finance->updateIncomeCategory($category->getKey(), $this->validated($request));

        return redirect()
            ->route('finance.income-categories.index')
            ->with('status', 'Income category updated.');
    }

    public function destroy(CategoryView $category): RedirectResponse
    {
        $this->authorize('finance.categories.manage');

        $this->finance->deleteIncomeCategory($category->getKey());

        return redirect()
            ->route('finance.income-categories.index')
            ->with('status', 'Income category deleted.');
    }

    /**
     * @return array<string, mixed>
     */
    private function validated(Request $request): array
    {
        return $request->validate([
            'name' => ['required', 'string', 'max:128'],
            'description' => ['nullable', 'string'],
            'is_active' => ['nullable', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0'],
        ]);
    }
}
