<?php

namespace App\Http\Controllers;

use App\Models\Department;
use App\Services\VisibilityService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class DepartmentCrudController extends Controller
{
    /** @var VisibilityService */
    private $visibility;

    public function __construct(VisibilityService $visibility)
    {
        $this->visibility = $visibility;
    }

    public function index()
    {
        $departments = Department::withCount('users')->orderBy('name')->get();

        return view('masters.departments.index', compact('departments'));
    }

    public function store(Request $request)
    {
        $validated = $this->validateDepartment($request);

        $department = Department::create($validated);
        $this->visibility->syncDepartmentPermissions($department->id, []);

        return redirect()->route('departments.master.index')->with('success', 'Department created.');
    }

    public function edit(Department $department)
    {
        return view('masters.departments.edit', compact('department'));
    }

    public function update(Request $request, Department $department)
    {
        $validated = $this->validateDepartment($request, $department->id);

        $department->update($validated);

        return redirect()->route('departments.master.index')->with('success', 'Department updated.');
    }

    public function destroy(Department $department)
    {
        if ($department->users()->exists()) {
            return redirect()->route('departments.master.index')->withErrors(['delete' => 'Cannot delete a department that has users assigned. Reassign users first.']);
        }

        $department->modulePermissions()->delete();
        $department->delete();

        return redirect()->route('departments.master.index')->with('success', 'Department deleted.');
    }

    private function validateDepartment(Request $request, ?int $ignoreId = null): array
    {
        $slugRule = \Illuminate\Validation\Rule::unique('departments', 'slug');
        if ($ignoreId) {
            $slugRule = $slugRule->ignore($ignoreId);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:120',
            'slug' => ['nullable', 'string', 'max:120', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slugRule],
            'description' => 'nullable|string|max:255',
            'is_active' => 'nullable|boolean',
        ]);

        $validated['slug'] = $validated['slug'] ?? Str::slug($validated['name']);
        $validated['is_active'] = (bool) $request->boolean('is_active', true);

        return $validated;
    }
}
