<?php

declare(strict_types=1);

namespace App\Http\Requests\Collections;

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

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

    protected function prepareForValidation(): void
    {
        foreach (['published_at', 'unpublished_at', 'archived_at', 'expired_at'] as $field) {
            if ($this->has($field) && trim((string) $this->input($field)) === '') {
                $this->merge([$field => null]);
            }
        }
    }

    public function rules(): array
    {
        return [
            'lifecycle_state' => ['nullable', 'in:' . implode(',', [
                Collection::LIFECYCLE_DRAFT,
                Collection::LIFECYCLE_SCHEDULED,
                Collection::LIFECYCLE_PUBLISHED,
                Collection::LIFECYCLE_FEATURED,
                Collection::LIFECYCLE_ARCHIVED,
                Collection::LIFECYCLE_EXPIRED,
            ])],
            'visibility' => ['nullable', 'in:' . implode(',', [
                Collection::VISIBILITY_PUBLIC,
                Collection::VISIBILITY_UNLISTED,
                Collection::VISIBILITY_PRIVATE,
            ])],
            'published_at' => ['nullable', 'date'],
            'unpublished_at' => ['nullable', 'date', 'after:published_at'],
            'archived_at' => ['nullable', 'date'],
            'expired_at' => ['nullable', 'date'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator): void {
            if ($this->filled('unpublished_at')) {
                $collection = $this->route('collection');

                if (! $this->filled('published_at') && ! optional($collection)->published_at) {
                    $validator->errors()->add('published_at', 'Set a publish time before adding an unpublish time.');
                }
            }
        });
    }
}