<?php

namespace App\Http\Controllers;

use App\Concerns\HasWorkspaceScope;
use App\Models\Declaration;
use App\Notifications\NudgeNotification;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class NudgeController extends Controller
{
    use HasWorkspaceScope;

    public function store(Request $request, Declaration $declaration): RedirectResponse
    {
        $this->authorizeWorkspaceAccess($declaration);

        $workspace = $this->currentWorkspace();

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

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

        $assignee = $declaration->assignee;

        if (! $assignee) {
            return back()->with('flash', ['type' => 'warning', 'message' => 'Cette déclaration n\'a pas de collaborateur assigné.']);
        }

        $recentNudge = $assignee
            ->notifications()
            ->where('type', NudgeNotification::class)
            ->where('data->declaration_id', $declaration->id)
            ->where('created_at', '>=', now()->subHour())
            ->exists();

        if ($recentNudge) {
            return back()->with('flash', ['type' => 'warning', 'message' => 'Relance déjà envoyée récemment']);
        }

        $assignee->notify(new NudgeNotification($declaration, $request->user()));

        activity()
            ->performedOn($declaration)
            ->causedBy($request->user())
            ->log('nudged');

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

        return back()->with('flash', ['type' => 'success', 'message' => 'Relance envoyée à '.$assignee->name]);
    }
}
