<?php

namespace App\Http\Requests\Store;

use App\Models\ClientAuthorization;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;

class SwitchAccountRequest extends FormRequest
{
    public function authorize(): bool
    {
        // Must be authenticated
        if (! Auth::guard('client')->check()) {
            return false;
        }

        $authenticatedClient = Auth::guard('client')->user();
        $targetClientId = $this->input('client_id');

        // Can always switch back to own account
        if ($targetClientId == $authenticatedClient->id) {
            return true;
        }

        // Must have valid authorization
        return ClientAuthorization::where('owner_client_id', $targetClientId)
            ->where('authorized_client_id', $authenticatedClient->id)
            ->where('status', 'active')
            ->whereNull('revoked_at')
            ->exists();
    }

    public function rules(): array
    {
        return [
            'client_id' => [
                'required',
                'integer',
                'exists:clients,id',
                function ($attribute, $value, $fail) {
                    // Additional security checks
                    $authenticatedClient = Auth::guard('client')->user();

                    // PRC-192: rolling 1-hour window (Cache) — eski session-bazlı
                    // sayaç logout'a kadar sıfırlanmıyor, çok-tenant yetkili
                    // kullanıcılar bloke oluyordu. Şimdi Redis/Cache TTL'i 1h.
                    $switchKey = 'client_switch_count:' . $authenticatedClient->id;
                    $switchCount = (int) \Cache::get($switchKey, 0);
                    if ($switchCount >= 20) { // Max 20 switches per rolling hour
                        $fail('Too many account switches in the past hour. Please wait.');

                        return;
                    }

                    // IP consistency check
                    $currentIp = $this->ip();
                    $loginIp = session('login_ip', $currentIp);
                    if ($currentIp !== $loginIp) {
                        $fail('IP address mismatch detected.');

                        return;
                    }

                    // User agent consistency (basic fingerprinting)
                    $currentUA = $this->userAgent();
                    $loginUA = session('login_user_agent', $currentUA);
                    if ($currentUA !== $loginUA) {
                        $fail('Session fingerprint mismatch.');

                        return;
                    }
                },
            ],
        ];
    }

    public function messages(): array
    {
        return [
            'client_id.required' => 'Client ID is required.',
            'client_id.integer' => 'Invalid client ID format.',
            'client_id.exists' => 'Client account not found.',
        ];
    }

    protected function failedAuthorization()
    {
        // Log unauthorized attempts
        \Log::warning('Unauthorized account switch attempt', [
            'authenticated_user' => Auth::guard('client')->id(),
            'target_client' => $this->input('client_id'),
            'ip' => $this->ip(),
            'user_agent' => $this->userAgent(),
        ]);
    }
}
