<?php

namespace App\Http\Requests\Api\Admin\Tools;

use App\APIClients\HttpMethod;
use App\Enums\Auth\Permissions;
use App\Http\Responses\Api\Player\Inbox\InboxMessageReward;
use Auth;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Carbon;
use Illuminate\Validation\Rule;

class InboxMessagePostRequest extends FormRequest
{
    public string $title;

    public string $body;

    public string $flag;

    public string $tag;

    public ?Carbon $expireAt;

    /** @var InboxMessageReward[]  */
    public array $rewards;

    public HttpMethod $submitAction;

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return Auth::check() && Auth::user()->can(Permissions::EDIT_USERS->value);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'title' => 'required|string',
            'body' => 'required|string',
            'flag' => ['required', Rule::in(['NEW', 'READ'])],
            'tag' => 'required|string',
            'expireAt' => 'sometimes|nullable|date',
            'rewards' => 'sometimes|array',
            'submitAction' =>  ['required', Rule::enum(HttpMethod::class)],
        ];
    }

    protected function passedValidation()
    {
        $this->title = $this->input('title');
        $this->body = $this->input('body');
        $this->flag = $this->input('flag');
        $this->tag = $this->input('tag');
        $this->expireAt = $this->has('expireAt') ? new Carbon($this->input('expireAt')) : null;
        $this->submitAction = HttpMethod::tryFrom($this->input('submitAction'));

        $rewardTypes = $this->input('rewards.type');
        $rewardIds = $this->input('rewards.id', []);
        $rewardAmounts = $this->input('rewards.amount');

        foreach ($rewardIds as $index => $id) {
            $this->rewards[] = new InboxMessageReward(
                $rewardTypes[$index],
                $rewardAmounts[$index],
                $id,
            );
        }
    }

    protected function failedValidation(Validator $validator)
    {
        \Session::flash('alert-error', $validator->errors()->first());

        parent::failedValidation($validator); // TODO: Change the autogenerated stub
    }
}
