<?php

namespace App\Http\Controllers\Api;

use App\Models\Maintenance;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MaintenanceController extends BaseApiController
{
    protected string $model = Maintenance::class;
    protected array $with = ['equipment'];
    protected array $searchable = ['technician', 'maintenanceType', 'notes'];
    protected array $filters = ['status' => 'status', 'equipment' => 'equipment_id'];

    protected function rules(Request $request, ?Model $model = null): array
    {
        return [
            'equipment' => 'nullable|string|exists:equipment,id',
            'maintenanceType' => 'nullable|string',
            'scheduledDate' => 'nullable|date',
            'technician' => 'nullable|string',
            'cost' => 'nullable|numeric',
            'notes' => 'nullable|string',
            'status' => 'nullable|string',
        ];
    }

    protected function transform(Request $request, array $data): array
    {
        if (array_key_exists('equipment', $data)) {
            $data['equipment_id'] = $data['equipment'];
            unset($data['equipment']);
        }
        return $data;
    }

    public function reschedule(Request $request, string $id): JsonResponse
    {
        $item = Maintenance::findOrFail($id);
        $data = $request->validate(['scheduledDate' => 'required|date']);
        $item->update(['scheduledDate' => $data['scheduledDate'], 'status' => 'Scheduled']);
        return response()->json($item->fresh(['equipment']));
    }
}
