<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreBranchRequest;
use App\Http\Requests\UpdateBranchRequest;
use App\Http\Resources\BranchResource;
use App\Http\Resources\BranchRowResource;
use App\Models\Branch;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class BranchController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Branch::query()->with('region')->orderBy('name')->limit(500);

        if ($request->filled('region_id')) {
            $query->where('region_id', $request->integer('region_id'));
        }

        if ($request->has('is_active')) {
            $query->where('is_active', $request->boolean('is_active'));
        }

        if ($request->filled('q')) {
            $term = $request->string('q').'%';
            $query->where(fn ($q) => $q->where('name', 'like', $term)->orWhere('code', 'like', $term));
        }

        $branches = $query->get();

        $resource = $request->query('fields') === 'basic'
            ? BranchRowResource::collection($branches)
            : BranchResource::collection($branches);

        return $resource->response();
    }

    public function show(Branch $branch): BranchResource
    {
        $this->authorize('view', $branch);

        $branch->load('region');
        $branch->members_count = Cache::remember(
            "branch:{$branch->id}:members_count",
            now()->addMinutes(10),
            fn () => $branch->members()->count(),
        );

        return new BranchResource($branch);
    }

    public function store(StoreBranchRequest $request): BranchResource
    {
        $branch = Branch::create($request->validated());

        return new BranchResource($branch->load('region'));
    }

    public function update(UpdateBranchRequest $request, Branch $branch): BranchResource
    {
        $branch->update($request->validated());

        return new BranchResource($branch->load('region'));
    }

    public function destroy(Branch $branch): JsonResponse
    {
        $this->authorize('delete', $branch);

        if ($branch->members()->exists()) {
            return response()->json(['message' => 'Cannot delete a branch that has members.'], 409);
        }

        $branch->delete();

        return response()->json(null, 204);
    }
}
