<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Operator;
use App\Http\Requests\OperatorRequest;
use App\Http\Resources\OperatorResource;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class OperatorController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        $query = Operator::query();

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'ILIKE', "%{$search}%")
                  ->orWhere('description', 'ILIKE', "%{$search}%");
            });
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('is_active', $request->get('status') === 'active');
        }

        $operators = $query->latest()->paginate(15);

        return response()->json([
            'data' => OperatorResource::collection($operators),
            'meta' => [
                'current_page' => $operators->currentPage(),
                'last_page' => $operators->lastPage(),
                'per_page' => $operators->perPage(),
                'total' => $operators->total(),
            ]
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(OperatorRequest $request): JsonResponse
    {
        $operator = Operator::create($request->validated());

        return response()->json([
            'message' => 'Operator created successfully',
            'data' => new OperatorResource($operator)
        ], 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(Operator $operator): JsonResponse
    {
        return response()->json([
            'data' => new OperatorResource($operator)
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(OperatorRequest $request, Operator $operator): JsonResponse
    {
        $operator->update($request->validated());

        return response()->json([
            'message' => 'Operator updated successfully',
            'data' => new OperatorResource($operator)
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Operator $operator): JsonResponse
    {
        $operator->delete();

        return response()->json([
            'message' => 'Operator deleted successfully'
        ]);
    }
}