<?php

namespace App\Http\Controllers;

use App\Services\BranchService;
use App\Http\Requests\Member\BranchStore;

class BranchController extends Controller
{

    private $branchService;

    public function __construct(BranchService $branchService)
    {
        $this->branchService = $branchService;

        $this->middleware('auth:sanctum');
    }

    public function index()
    {
        $branches = $this->branchService->getAll();

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

    public function store(BranchStore $request)
    {
        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isAdmin = auth()->user()->hasRole('admin');
        $isOperator = auth()->user()->hasRole('operator');

        if (!$isSuperAdmin && !$isAdmin && !$isOperator) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $branch = $this->branchService->save($request->all());

        return response()->json($branch, 201);
    }

    public function show($id)
    {
        $branch = $this->branchService->get($id);

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

    public function destroy($id)
    {
        $isSuperAdmin = auth()->user()->hasRole('super_admin');
        $isAdmin = auth()->user()->hasRole('admin');
        $isOperator = auth()->user()->hasRole('operator');

        if (!$isSuperAdmin && !$isAdmin && !$isOperator) {
            return response()->json(['message' => 'You have no rights to do this'], 401);
        }

        $this->branchService->delete($id);
        return response()->json(null, 204);
    }
}
