<?php

namespace App\Http\Controllers\Api;

use App\Models\SafetyIncident;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class SafetyController extends BaseApiController
{
    protected string $model = SafetyIncident::class;
    protected array $with = ['project'];
    protected array $searchable = ['title', 'incidentId', 'reportedBy'];
    protected array $filters = ['status' => 'status', 'severity' => 'severity', 'project' => 'project_id'];

    protected function rules(Request $request, ?Model $model = null): array
    {
        $required = $model ? 'sometimes' : 'required';
        return [
            'incidentId' => 'nullable|string',
            'title' => "$required|string",
            'description' => 'nullable|string',
            'severity' => 'nullable|string',
            'status' => 'nullable|string',
            'project' => 'nullable|string|exists:projects,id',
            'reportedBy' => 'nullable|string',
            'reportedDate' => 'nullable|date',
            'resolvedDate' => 'nullable|date',
            'location' => 'nullable|string',
        ];
    }

    protected function transform(Request $request, array $data): array
    {
        if (array_key_exists('project', $data)) {
            $data['project_id'] = $data['project'];
            unset($data['project']);
        }
        if (empty($data['incidentId']) && empty($request->route('id'))) {
            $data['incidentId'] = 'INC-' . str_pad((string) (SafetyIncident::withTrashed()->count() + 1), 4, '0', STR_PAD_LEFT);
        }
        return $data;
    }
}
