<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CropSizeRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        // Allow in local environment
        if (app()->environment('local')) {
            return true;
        }

        // Allow authenticated admin users
        if (auth()->check()) {
            return true;
        }

        // Validate token for public/frontend requests
        $encryption_string = config('media.crop_hash') . ':' . $this->mediaUse->id
            . ':' . $this->input('width') . ':' . $this->input('height');
        return $this->mediaUse
            && $this->input('token')
            && $this->input('token') === md5($encryption_string);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $isAuthenticated = auth()->check() || app()->environment('local');

        return [
            'tenant' => $isAuthenticated ? 'nullable' : 'required',
            'token' => $isAuthenticated ? 'nullable' : 'required',
            'width' => [
                'required',
                'numeric',
                'min:1',
                'max:4000',
            ],
            'height' => [
                'required',
                'numeric',
                'min:1',
                'max:4000',
            ],
            'coordinates' => 'nullable|array',
            'coordinates.x' => 'required_with:coordinates|numeric|min:0',
            'coordinates.y' => 'required_with:coordinates|numeric|min:0',
            'coordinates.width' => 'required_with:coordinates|numeric|min:1',
            'coordinates.height' => 'required_with:coordinates|numeric|min:1',
        ];
    }
}
