<?php

namespace App\Http\Requests\Admin;

use App\Http\Requests\Admin\Concerns\AdminAccountFieldRules;
use App\Http\Requests\Admin\Concerns\AgentProfileFieldRules;
use App\Http\Requests\ApiFormRequest;
use App\Models\AdminSite;
use App\Models\AgentNode;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

final class AdminAgentLineStoreRequest extends ApiFormRequest
{
    use AdminAccountFieldRules;
    use AgentProfileFieldRules;

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

    protected function prepareForValidation(): void
    {
        $this->normalizeAdminAccountFields();
        $this->prepareAgentProfileFieldsForValidation();

        if ($this->has('site_code')) {
            $this->merge([
                'site_code' => strtolower(trim((string) $this->input('site_code'))),
            ]);
        }

        if ($this->has('code')) {
            $this->merge([
                'code' => strtolower(trim((string) $this->input('code'))),
            ]);
        }
    }

    /** @return array<string, mixed> */
    public function rules(): array
    {
        return [
            'site_code' => ['required', 'string', 'max:64', 'regex:/^[a-z0-9][a-z0-9_-]*$/', Rule::exists('admin_sites', 'code')],
            'code' => ['sometimes', 'nullable', 'string', 'max:64', 'regex:/^[a-z0-9][a-z0-9_-]*$/', Rule::unique('agent_nodes', 'code')],
            'name' => ['required', 'string', 'max:128'],
            'username' => [...$this->adminOperatorUsernameRules(), Rule::unique('admin_users', 'username')],
            'password' => $this->adminLoginPasswordRules(),
            'email' => ['nullable', 'string', 'email', 'max:255', Rule::unique('admin_users', 'email')],
            'status' => ['sometimes', 'integer', 'in:0,1'],
            ...$this->agentProfileFieldRules(),
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            if ($validator->errors()->isNotEmpty()) {
                return;
            }

            $siteCode = (string) $this->input('site_code');
            $site = AdminSite::query()->where('code', $siteCode)->first();
            if ($site === null) {
                return;
            }

            $hasRoot = AgentNode::query()
                ->where('admin_site_id', $site->id)
                ->where('depth', 0)
                ->exists();

            if ($hasRoot) {
                $validator->errors()->add('site_code', 'site_root_exists');
            }
        });
    }
}
