<?php

namespace App\Http\Controllers;

use App\Models\DepartmentModulePermission;
use App\Models\UserModuleOverride;
use App\Models\VisibilityModule;
use App\Services\VisibilityService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

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

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

    public function index()
    {
        $modules = VisibilityModule::orderBy('sort_order')->orderBy('group')->orderBy('label')->get();

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

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

        $module = VisibilityModule::create($validated);
        $this->visibility->provisionModulePermissions($module->key);

        return redirect()->route('visibility-modules.index')->with('success', 'Module "' . $module->key . '" created. Assign it to departments in Visibility Manager.');
    }

    public function edit(VisibilityModule $visibilityModule)
    {
        return view('masters.modules.edit', ['module' => $visibilityModule]);
    }

    public function update(Request $request, VisibilityModule $visibilityModule)
    {
        $validated = $this->validateModule($request, $visibilityModule->id);

        $oldKey = $visibilityModule->key;
        $visibilityModule->update($validated);

        if ($oldKey !== $visibilityModule->key) {
            DepartmentModulePermission::where('module_key', $oldKey)->update(['module_key' => $visibilityModule->key]);
            UserModuleOverride::where('module_key', $oldKey)->update(['module_key' => $visibilityModule->key]);
        }

        return redirect()->route('visibility-modules.index')->with('success', 'Module updated.');
    }

    public function destroy(VisibilityModule $visibilityModule)
    {
        $this->visibility->removeModulePermissions($visibilityModule->key);
        $visibilityModule->delete();

        return redirect()->route('visibility-modules.index')->with('success', 'Module removed.');
    }

    private function validateModule(Request $request, ?int $ignoreId = null): array
    {
        $keyRule = Rule::unique('visibility_modules', 'key');
        if ($ignoreId) {
            $keyRule = $keyRule->ignore($ignoreId);
        }

        $validated = $request->validate([
            'key' => ['required', 'string', 'max:80', 'regex:/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/', $keyRule],
            'label' => 'required|string|max:120',
            'group' => 'required|string|max:80',
            'description' => 'nullable|string|max:255',
            'sort_order' => 'nullable|integer|min:0|max:9999',
        ]);

        $validated['is_active'] = $request->boolean('is_active', true);
        $validated['sort_order'] = (int) ($validated['sort_order'] ?? 0);

        return $validated;
    }
}
