<?php

namespace Modules\Accounts\Http\Requests\Account;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Accounts\Models\ChartOfAccount;
use Modules\Core\Traits\FailedValidation;

class UpdateAccountRequest extends FormRequest
{
    use FailedValidation;

    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $accountId = $this->route('account')?->id ?? $this->route('account');

        return [
            'account_code' => ['sometimes', 'nullable', 'integer', Rule::unique('chart_of_accounts', 'account_code')->ignore($accountId)],
            'account_name' => ['sometimes', 'string', 'max:255'],
            'parent_id' => ['sometimes', 'nullable', 'integer', 'exists:chart_of_accounts,id'],
            'is_group' => ['sometimes', 'boolean'],
            'account_type' => ['sometimes', Rule::in(['Asset', 'Liability', 'Equity', 'Income', 'Expense'])],
            'is_cash' => ['sometimes', 'boolean'],
            'is_bank' => ['sometimes', 'boolean'],
            'description' => ['sometimes', 'nullable', 'string'],
            'status' => ['sometimes', 'boolean'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            if (! $this->has('parent_id')) {
                return;
            }

            $accountId = $this->route('account')?->id ?? $this->route('account');
            $parentId = $this->input('parent_id');

            if ($parentId === null) {
                return;
            }

            if ((int) $parentId === (int) $accountId) {
                $validator->errors()->add('parent_id', 'An account cannot be its own parent.');
                return;
            }

            $parent = ChartOfAccount::query()->find($parentId);

            if ($parent !== null && ! $parent->is_group) {
                $validator->errors()->add('parent_id', 'Ledger accounts cannot have child accounts.');
            }
        });
    }
}
