<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreDeclarationMentionRequest;
use App\Models\Declaration;
use App\Models\User;
use App\Models\Workspace;
use App\Notifications\DeclarationMentionNotification;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

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

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

    protected function authorizeDeclaration(Workspace $workspace, Declaration $declaration): void
    {
        if ($declaration->workspace_id !== $workspace->id) {
            abort(404);
        }
    }

    public function store(StoreDeclarationMentionRequest $request, Declaration $declaration): RedirectResponse
    {
        $workspace = $this->currentWorkspace($request);
        $this->authorizeDeclaration($workspace, $declaration);

        $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 DeclarationMentionNotification(
            $declaration,
            $request->user(),
            $validated['message'],
        ));

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

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