<?php

namespace Modules\Accounts\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Modules\Accounts\DTO\AccountIndexFilter;
use Modules\Accounts\Http\Requests\Account\StoreAccountRequest;
use Modules\Accounts\Http\Requests\Account\UpdateAccountRequest;
use Modules\Accounts\Models\ChartOfAccount;
use Modules\Accounts\Services\AccountService;
use Modules\Accounts\Transformers\AccountResource;
use Modules\Core\Helpers\ApiResponse;

class AccountController extends Controller
{
    use AuthorizesRequests;

    protected $accounts;

    public function __construct(AccountService $accounts)
    {
        $this->accounts = $accounts;
    }

    public function index(Request $request)
    {
        $this->authorize('viewAny', ChartOfAccount::class);
        $filters = AccountIndexFilter::fromRequest($request);

        return AccountResource::collection($this->accounts->list($filters))->additional([
            'status' => true,
            'message' => 'Accounts retrieved successfully.',
        ]);
    }

    public function tree(Request $request)
    {
        $this->authorize('tree', ChartOfAccount::class);

        return ApiResponse::successResponse(
            message: 'Account tree retrieved successfully.',
            data: $this->accounts->buildTreeArray($request->query('search'))
        );
    }

    public function store(StoreAccountRequest $request)
    {
        $this->authorize('create', ChartOfAccount::class);

        return (new AccountResource($this->accounts->store($request->validated())->load(['parent'])))->additional([
            'status' => true,
            'message' => 'Account created successfully.',
        ]);
    }

    public function show(ChartOfAccount $account)
    {
        $this->authorize('viewAny', ChartOfAccount::class);

        return (new AccountResource($this->accounts->show($account->id)))->additional([
            'status' => true,
            'message' => 'Account retrieved successfully.',
        ]);
    }

    public function update(UpdateAccountRequest $request, ChartOfAccount $account)
    {
        $this->authorize('update', $account);

        return (new AccountResource($this->accounts->update($account, $request->validated())))->additional([
            'status' => true,
            'message' => 'Account updated successfully.',
        ]);
    }

    public function destroy(ChartOfAccount $account)
    {
        $this->authorize('delete', $account);

        $this->accounts->delete($account);

        return ApiResponse::successResponse('Account deleted successfully.');
    }
}
