<?php

namespace App\Http\Requests;

use App\Services\Settings\SettingsService;
use Illuminate\Foundation\Http\FormRequest;

class StoreResumeRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        $settings = app(SettingsService::class);

        return $this->user() !== null
            && $this->user()->hasUnlockedAccess()
            && (! $this->user()->hasUploadedResume() || $settings->isEnabled('resume.allow_resume_re_upload'));
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $settings = app(SettingsService::class);
        $allowedFileTypes = $this->allowedFileTypes($settings);
        $maximumFileSizeKb = max(1, (int) $settings->get('resume.maximum_file_size_mb', 5)) * 1024;

        return [
            'resume' => [
                'required',
                'file',
                'mimes:'.implode(',', $allowedFileTypes),
                'max:'.$maximumFileSizeKb,
            ],
        ];
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'resume' => 'resume',
        ];
    }

    /**
     * @return array<int, string>
     */
    private function allowedFileTypes(SettingsService $settings): array
    {
        $allowedFileTypes = collect($settings->get('resume.allowed_file_types', ['pdf', 'doc', 'docx']))
            ->map(fn (string $type): string => strtolower(trim($type, ". \t\n\r\0\x0B")))
            ->filter(fn (string $type): bool => in_array($type, ['pdf', 'doc', 'docx', 'txt'], true))
            ->unique()
            ->values()
            ->all();

        return $allowedFileTypes === [] ? ['pdf', 'doc', 'docx'] : $allowedFileTypes;
    }
}
