<?php

namespace App\Modules\HR\Assets\Requests;

use App\Modules\HR\Assets\Models\Asset;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class AssetRequest extends FormRequest
{
    public function authorize(): bool
    {
        $asset = $this->route('asset');

        return $asset instanceof Asset
            ? ($this->user()?->can('update', $asset) ?? false)
            : ($this->user()?->can('create', Asset::class) ?? false);
    }

    public function rules(): array
    {
        $asset = $this->route('asset');
        $unique = Rule::unique('hr_assets', 'asset_code')
            ->where(fn ($q) => $q->where('tenant_id', $this->user()?->tenant_id))
            ->ignore($asset instanceof Asset ? $asset->id : null);

        return [
            'category' => ['required', 'string', 'max:120'],
            'asset_code' => ['required', 'string', 'max:120', $unique],
            'name' => ['required', 'string', 'max:255'],
            'serial_number' => ['nullable', 'string', 'max:255'],
            'status' => ['sometimes', Rule::in(['available', 'maintenance', 'damaged', 'retired', 'lost'])],
            'purchase_date' => ['nullable', 'date'],
            'warranty_until' => ['nullable', 'date', 'after_or_equal:purchase_date'],
            'location' => ['nullable', 'string', 'max:255'],
            'notes' => ['nullable', 'string', 'max:5000'],
        ];
    }
}
