<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreFolderMentionRequest;
use App\Models\Folder;
use App\Models\User;
use App\Models\Workspace;
use App\Notifications\FolderMentionNotification;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class FolderMentionController extends Controller
{
    protected function currentWorkspace(Request $request): Workspace
    {
        $workspaceId = $request->session()->get('current_workspace_id');

        return Workspace::query()->findOrFail($workspaceId);
    }

    protected function authorizeFolder(Workspace $workspace, Folder $folder): void
    {
        if ($folder->workspace_id !== $workspace->id) {
            abort(404);
        }
    }

    public function store(StoreFolderMentionRequest $request, Folder $folder): RedirectResponse
    {
        $workspace = $this->currentWorkspace($request);
        $this->authorizeFolder($workspace, $folder);

        $userRole = $workspace->users()
            ->where('users.id', $request->user()->id)
            ->first()
            ?->pivot
            ?->role
            ?->value;

        if (! in_array($userRole, ['owner', 'manager'])) {
            abort(403);
        }

        $validated = $request->validated();
        $targetUser = User::findOrFail($validated['user_id']);

        $targetUser->notify(new FolderMentionNotification(
            $folder,
            $request->user(),
            $validated['message'],
        ));

        Cache::forget("user:{$targetUser->id}:workspace:{$workspace->id}:unread_notifications");

        return back()->with('flash', ['type' => 'success', 'message' => 'Notification envoyée.']);
    }
}
