<?php

declare(strict_types=1);

namespace App\Http\Requests\Asset;

use App\Enums\AssetCondition;
use App\Enums\AssetDocumentType;
use App\Enums\AssetStatus;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    /**
     * @return array<string, array<int, mixed>>
     */
    public function rules(): array
    {
        return [
            'asset_tag' => [
                'nullable',
                'string',
                'max:40',
                // Letters, numbers, hyphens and slashes — slashes because
                // this organisation's own tag convention uses them
                // (e.g. "AT/MAC/001").
                'regex:/^[A-Z0-9\-\/]+$/',
                Rule::unique('assets', 'asset_tag'),
            ],
            'name' => ['required', 'string', 'max:150'],
            'serial_number' => [
                'nullable',
                'string',
                'max:100',
                // Unique across all rows, soft-deleted included: a serial
                // reused from a disposed asset's row would collide on restore.
                Rule::unique('assets', 'serial_number'),
            ],
            // No format enforced — see AssetRules::normaliseMacAddress().
            'mac_address' => [
                'nullable',
                'string',
                'max:32',
                Rule::unique('assets', 'mac_address'),
            ],
            'category_id' => [
                'required',
                'integer',
                Rule::exists('asset_categories', 'id')->whereNull('deleted_at'),
            ],
            'manufacturer' => ['nullable', 'string', 'max:100'],
            'model' => ['nullable', 'string', 'max:120'],
            'vendor' => ['nullable', 'string', 'max:150'],
            'location_id' => [
                'nullable',
                'integer',
                Rule::exists('locations', 'id')->whereNull('deleted_at'),
            ],
            'team_id' => [
                'nullable',
                'integer',
                Rule::exists('teams', 'id')->whereNull('deleted_at'),
            ],
            // Only the statuses an asset may start its life in. Assigned,
            // lost, retired and disposed are all reached only via a later
            // transition — see AssetStatus::assignableOnCreate().
            'status' => [
                'required',
                Rule::in(array_map(static fn (AssetStatus $status): string => $status->value, AssetStatus::assignableOnCreate())),
            ],
            'condition' => ['required', Rule::enum(AssetCondition::class)],
            'purchase_date' => ['nullable', 'date', 'before_or_equal:today'],
            'purchase_cost' => ['nullable', 'numeric', 'min:0', 'max:99999999999.99'],
            'currency' => ['required', 'string', 'size:3'],
            'invoice_number' => ['nullable', 'string', 'max:60'],
            'po_number' => ['nullable', 'string', 'max:60'],
            'notes' => ['nullable', 'string', 'max:5000'],
            'is_active' => ['required', 'boolean'],
            'specifications' => ['nullable', 'array'],
            'specifications.*' => ['string', 'max:255'],
            // Optional: filled in together, they create the asset's initial
            // Manufacturer Warranty record — see AssetController::store().
            // Left blank, no warranty is created; the asset is not held up
            // waiting on cover details it may not have yet.
            'warranty_start_date' => ['nullable', 'date', 'required_with:warranty_end_date'],
            'warranty_end_date' => ['nullable', 'date', 'after:warranty_start_date', 'required_with:warranty_start_date'],
            // Optional: an invoice, PO or other document to attach at the
            // moment the asset is created — see AssetController::store().
            // Left blank, no document is attached; the asset is not held up
            // waiting on paperwork it may not have yet.
            'document' => ['nullable', 'file', 'mimes:pdf,jpg,jpeg,png', 'max:10240'],
            'document_type' => ['nullable', Rule::enum(AssetDocumentType::class)],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'asset_tag.unique' => __('An asset with this tag already exists.'),
            'asset_tag.regex' => __('Asset tags may only contain letters, numbers, hyphens and slashes.'),
            'serial_number.unique' => __('An asset with this serial number already exists. It may be in the deleted list.'),
            'mac_address.unique' => __('An asset with this MAC address already exists.'),
            'category_id.exists' => __('The selected category no longer exists.'),
            'location_id.exists' => __('The selected location no longer exists.'),
            'team_id.exists' => __('The selected team no longer exists.'),
            'purchase_date.before_or_equal' => __('The purchase date cannot be in the future.'),
            'warranty_start_date.required_with' => __('Enter both warranty dates, or leave both blank.'),
            'warranty_end_date.required_with' => __('Enter both warranty dates, or leave both blank.'),
            'warranty_end_date.after' => __('The warranty end date must be after the start date.'),
            'document.mimes' => __('The document must be a PDF, JPG or PNG file.'),
            'document.max' => __('The document cannot be larger than 10 MB.'),
        ];
    }

    protected function prepareForValidation(): void
    {
        $this->merge(AssetRules::normalise($this));
    }
}
