<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Request;

use apexl\Io\modules\userDisplay\FormBuilders\LoginFormBuilder;
use apexl\Io\modules\validation\Interfaces\HasValidationRulesInterface;
use apexl\Io\modules\validation\Interfaces\ValidatesDataInterface;
use apexl\Io\modules\validation\Traits\ValidatesData;
use apexl\Io\Request\IoRequest;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
use Slim\Psr7\Interfaces\HeadersInterface;

final class LoginRequest extends IoRequest implements ValidatesDataInterface
{
    use ValidatesData;

    public function __construct(
        $method,
        UriInterface $uri,
        HeadersInterface $headers,
        array $cookies,
        array $serverParams,
        StreamInterface $body,
        array $uploadedFiles,
        private readonly LoginFormBuilder $formBuilder,
    ) {
        parent::__construct(
            $method,
            $uri,
            $headers,
            $cookies,
            $serverParams,
            $body,
            $uploadedFiles,
        );
    }

    public function username(): string
    {
        return $this->bodyParam('username', '');
    }

    public function password(): string
    {
        return $this->bodyParam('password', '');
    }

    public function redirect(): ?string
    {
        return $this->bodyParam('redirect') ?: '/';
    }

    /**
     * "Stay signed in" (remember-me). A form checkbox posts "true"/"1"/"on"; an
     * SPA may post a real boolean. Accept the usual truthy shapes. Absent =
     * false (a normal, session-length login).
     */
    public function remember(): bool
    {
        return filter_var($this->bodyParam('remember', false), FILTER_VALIDATE_BOOLEAN);
    }

    public function validationRules(): HasValidationRulesInterface
    {
        return $this->formBuilder;
    }
}
