<?php

declare(strict_types=1);

namespace App\Http\Requests\Collections;

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

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

    public function rules(): array
    {
        return [
            'action' => ['required', 'string', 'in:archive,assign_campaign,update_lifecycle,request_ai_review,mark_editorial_review'],
            'collection_ids' => ['required', 'array', 'min:1'],
            'collection_ids.*' => ['integer', 'distinct'],
            'campaign_key' => ['nullable', 'string', 'max:80'],
            'campaign_label' => ['nullable', 'string', 'max:120'],
            'lifecycle_state' => ['nullable', 'string', 'in:' . implode(',', [
                Collection::LIFECYCLE_DRAFT,
                Collection::LIFECYCLE_PUBLISHED,
                Collection::LIFECYCLE_ARCHIVED,
            ])],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator): void {
            $action = (string) $this->input('action', '');

            if ($action === 'assign_campaign' && blank($this->input('campaign_key'))) {
                $validator->errors()->add('campaign_key', 'Campaign key is required for campaign assignment.');
            }

            if ($action === 'update_lifecycle' && blank($this->input('lifecycle_state'))) {
                $validator->errors()->add('lifecycle_state', 'Lifecycle state is required for lifecycle updates.');
            }
        });
    }
}