<?php

namespace App\Http\Controllers;

use App\Http\Requests\BranchRequest;
use App\Models\Branch;
use App\Services\BranchService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

class BranchController extends Controller implements HasMiddleware
{
    public function __construct(private BranchService $service)
    {
    }

    public static function middleware(): array
    {
        return [
            new Middleware('can:viewAny,'.Branch::class, only: ['index']),
            new Middleware('can:create,'.Branch::class, only: ['create', 'store']),
            new Middleware('can:view,branch', only: ['show']),
            new Middleware('can:update,branch', only: ['edit', 'update']),
            new Middleware('can:delete,branch', only: ['destroy']),
        ];
    }

    public function index(): View
    {
        $branches = $this->service->accessibleQuery()->orderBy('name')->get();

        return view('branches.index', compact('branches'));
    }

    public function create(): View
    {
        return view('branches.create', ['branch' => new Branch()]);
    }

    public function store(BranchRequest $request): RedirectResponse
    {
        $this->service->create($request->validated());

        return redirect()->route('branches.index')->with('success', 'Branch created successfully.');
    }

    public function show(Branch $branch): View
    {
        $branch->loadCount(['users', 'staff']);

        return view('branches.show', compact('branch'));
    }

    public function edit(Branch $branch): View
    {
        return view('branches.edit', compact('branch'));
    }

    public function update(BranchRequest $request, Branch $branch): RedirectResponse
    {
        $this->service->update($branch->id, $request->validated());

        return redirect()->route('branches.index')->with('success', 'Branch updated successfully.');
    }

    public function destroy(Branch $branch): RedirectResponse
    {
        if ($branch->users()->exists()) {
            return back()->with('error', 'Cannot delete a branch that still has users assigned.');
        }

        $this->service->delete($branch->id);

        return redirect()->route('branches.index')->with('success', 'Branch deleted.');
    }
}
