<?php

namespace App\Modules\Province\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Province\Models\Province;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ProvinceController extends Controller
{
    /**
     * LIST provinces (etraplar)
     */
    public function index(Request $request): JsonResponse
    {
        $request->validate([
            'groupBy' => ['nullable', 'string', 'in:region'],
        ]);

        $provinces = Province::query()
            ->where('active', true)
            ->get()
            ->map(fn (Province $province) => [
                'id' => $province->id,
                'name' => $province->name,
                'region' => $province->region,
            ]);

        if ($request->filled('groupBy')) {
            $provinces = $provinces->groupBy('region');
        }

        return response()->json($provinces);
    }
}
