<?php

declare(strict_types=1);

namespace App\Http\Requests\Groups;

use App\Models\Group;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;

class StoreGroupRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    protected function prepareForValidation(): void
    {
        $name = (string) $this->input('name', '');
        $slug = (string) $this->input('slug', '');

        if ($slug === '' && $name !== '') {
            $slug = Str::slug(Str::limit($name, 90, ''));
        }

        $this->merge([
            'slug' => $slug,
        ]);
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'min:2', 'max:80'],
            'slug' => ['required', 'string', 'min:2', 'max:90', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/'],
            'headline' => ['nullable', 'string', 'max:160'],
            'bio' => ['nullable', 'string', 'max:3000'],
            'visibility' => ['required', 'in:' . implode(',', Group::acceptedVisibilityValues())],
            'membership_policy' => ['nullable', 'in:' . implode(',', Group::acceptedMembershipPolicies())],
            'type' => ['nullable', 'string', 'max:80'],
            'founded_at' => ['nullable', 'date'],
            'website_url' => ['nullable', 'url', 'max:2048'],
            'links_json' => ['nullable', 'array', 'max:8'],
            'links_json.*.label' => ['required_with:links_json', 'string', 'max:40'],
            'links_json.*.url' => ['required_with:links_json', 'url', 'max:2048'],
            'avatar_path' => ['nullable', 'string', 'max:2048'],
            'banner_path' => ['nullable', 'string', 'max:2048'],
            'avatar_file' => ['nullable', 'file', 'image', 'max:5120', 'mimes:jpg,jpeg,png,webp'],
            'banner_file' => ['nullable', 'file', 'image', 'max:5120', 'mimes:jpg,jpeg,png,webp'],
        ];
    }
}