<?php

declare(strict_types=1);

namespace App\Http\Requests\Collections;

use App\Models\Collection;
use Illuminate\Foundation\Http\FormRequest;

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

    protected function prepareForValidation(): void
    {
        foreach ([
            'event_key',
            'event_label',
            'season_key',
            'banner_text',
            'badge_label',
            'campaign_key',
            'campaign_label',
            'promotion_tier',
            'sponsorship_label',
            'partner_label',
            'monetization_ready_status',
            'brand_safe_status',
            'editorial_notes',
            'staff_commercial_notes',
        ] as $field) {
            if ($this->has($field) && trim((string) $this->input($field)) === '') {
                $this->merge([$field => null]);
            }
        }
    }

    public function rules(): array
    {
        return [
            'event_key' => ['nullable', 'string', 'max:80'],
            'event_label' => ['nullable', 'string', 'max:120'],
            'season_key' => ['nullable', 'string', 'max:80'],
            'banner_text' => ['nullable', 'string', 'max:200'],
            'badge_label' => ['nullable', 'string', 'max:80'],
            'spotlight_style' => ['nullable', 'in:' . implode(',', [
                Collection::SPOTLIGHT_STYLE_DEFAULT,
                Collection::SPOTLIGHT_STYLE_EDITORIAL,
                Collection::SPOTLIGHT_STYLE_SEASONAL,
                Collection::SPOTLIGHT_STYLE_CHALLENGE,
                Collection::SPOTLIGHT_STYLE_COMMUNITY,
            ])],
            'campaign_key' => ['nullable', 'string', 'max:80'],
            'campaign_label' => ['nullable', 'string', 'max:120'],
            'commercial_eligibility' => ['nullable', 'boolean'],
            'promotion_tier' => ['nullable', 'string', 'max:40'],
            'sponsorship_label' => ['nullable', 'string', 'max:120'],
            'partner_label' => ['nullable', 'string', 'max:120'],
            'monetization_ready_status' => ['nullable', 'string', 'max:40'],
            'brand_safe_status' => ['nullable', 'string', 'max:40'],
            'editorial_notes' => ['nullable', 'string', 'max:2000'],
            'staff_commercial_notes' => ['nullable', 'string', 'max:2000'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator): void {
            if ($this->filled('staff_commercial_notes') && ! $this->user()?->isAdmin()) {
                $validator->errors()->add('staff_commercial_notes', 'Only admins can update staff commercial notes.');
            }
        });
    }
}
