<?php

namespace App\Http\Controllers;

use App\Events\NotificationCreated;
use App\Models\Followee;
use App\Models\Notification;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate;

class FollowerController extends Controller
{
    public function index(): JsonResponse
    {
        $followers = Followee::with('user')
            ->where('followee_id', auth()->id())
            ->orderBy('verified') // unverified first
            ->get()
            ->map(fn (Followee $f) => [
                'user'     => $f->user,
                'verified' => $f->verified,
            ]);

        return response()->json($followers);
    }

    public function follow(User $user): JsonResponse
    {
        abort_if($user->id === auth()->id(), 403);

        $existing = Followee::where('user_id', auth()->id())
            ->where('followee_id', $user->id)
            ->first();

        if ($existing) {
            $existing->delete();
            $this->clearFollowingCache(auth()->user());

            Notification::where('user_id', $user->id)
                ->whereIn('title', ['New follower', 'Follow request'])
                ->where('url', $canView ?? true
                    ? '/u/' . auth()->user()->name
                    : '/follow-requests')
                ->delete();

            return response()->json(['status' => 'none']);
        }

        $canView = Gate::allows('viewProfileData', $user);

        Followee::create([
            'user_id'     => auth()->id(),
            'followee_id' => $user->id,
            'verified'    => $canView,
        ]);

        $this->clearFollowingCache(auth()->user());

        if($user->getSetting('notify_on_new_follower')) {
            Notification::create([
                'user_id' => $user->id,
                'title' => $canView ? 'New follower' : 'Follow request',
                'body' => $canView
                    ? auth()->user()->name . ' is now following you.'
                    : auth()->user()->name . ' wants to follow you.',
                'is_achievement' => false,
                'url' => $canView ? '/u/' . auth()->user()->name : '/settings/followers',
            ]);
        }

        return response()->json(['status' => $canView ? 'following' : 'requested']);
    }

    public function approve(User $follower): JsonResponse
    {
        $followee = Followee::where('user_id', $follower->id)
            ->where('followee_id', auth()->id())
            ->pending()
            ->firstOrFail();

        $followee->update(['verified' => true]);

        $this->clearFollowingCache($follower);

        Notification::create([
            'user_id'        => $follower->id,
            'title'          => 'Follow request accepted',
            'body'           => auth()->user()->name . ' accepted your follow request.',
            'is_achievement' => false,
            'url'            => '/u/' . auth()->user()->name,
        ]);

        return response()->json(['status' => 'approved']);
    }

    public function deny(User $follower): JsonResponse
    {
        Followee::where('user_id', $follower->id)
            ->where('followee_id', auth()->id())
            ->pending()
            ->delete();

        $this->clearFollowingCache($follower);

        return response()->json(['status' => 'denied']);
    }

    public function remove(User $follower): JsonResponse
    {
        Followee::where('user_id', $follower->id)
            ->where('followee_id', auth()->id())
            ->verified()
            ->delete();

        $this->clearFollowingCache($follower);

        return response()->json(['status' => 'removed']);
    }

    protected function clearFollowingCache(User $user): void
    {
        Cache::forget("user:{$user->id}:following");
        Cache::forget("user_following_flights_{$user->id}");
    }
}
