<?php

namespace App\Modules\Branch\Controllers;

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

class BranchController extends Controller
{
    /**
     * LIST branches
     *
     * Bank şahamçalary. http://online.tbbank.gov.tm/work-place/resources/branches
     */
    public function index(Request $request): JsonResponse
    {
        $request->validate([
            'groupBy' => ['nullable', 'string', 'in:region'],
        ]);

        $branches = Branch::query()
            ->where('active', true)
            ->get()
            ->map(fn ($branch) => [
                'id' => $branch->id,
                'name' => $branch->name,
                'region' => $branch->region,
            ]);

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

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