<?php

namespace LaraBB\Tracker\UI\Web\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Rhilip\Bencode\Bencode;

/**
 *
 */
class Announce extends FormRequest
{
    /**
     * @return bool
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * @return string[]
     */
    public function rules(): array
    {
        return [
            'pid'      => 'required|exists:users,pid',
            'infohash' => 'required|exists:users_torrents,infohash',
            'port'     => 'required'
        ];
    }

    /**
     * @return array|string[]
     */
    public function messages(): array
    {
        return [
            'pid.required'      => Bencode::encode(['failure reason' => 'PID is missing. Please redownload the torrent.']),
            'pid.exists'        => Bencode::encode(['failure reason' => 'There is no user with this PID.']),
            'infohash.required' => Bencode::encode(['failure reason' => 'Torrent info hash is missing. Please redownload the torrent.']),
            'infohash.exists'   => Bencode::encode(['failure reason' => 'This torrent is not registered on our tracker.']),
            'port'              => 'Parameter "port" is missing in request.'
        ];
    }

    public function all($keys = null): array
    {
        $data             = parent::all($keys);
        $data['pid']      = $this->route('pid');
        $data['infohash'] = bin2hex($this->get('info_hash'));
        $data['port']     = $this->get('port');

        return $data;
    }
}
