<?php

namespace App\Http\Controllers;

use App\Enums\FollowStatus;
use App\Http\Requests\FollowRequest;
use App\Http\Resources\FollowResource;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class FollowController extends Controller
{
    public function follow(FollowRequest $request, User $user): JsonResponse
    {
        $authUser = $request->user();

        if ($authUser->id === $user->id) {
            return response()->json([
                'message' => __('api.follows.cannot_follow_self')
            ], 422);
        }

        // Default to Accepted as is_private doesn't exist in the DB yet
        $status = FollowStatus::Accepted;

        $authUser->following()->syncWithPivotValues([$user->id], ['status' => $status], false);

        return response()->json([
            'message' => __('api.follows.followed'),
            'status' => $status,
        ]);
    }

    public function unfollow(FollowRequest $request, User $user): JsonResponse
    {
        $request->user()->following()->detach($user->id);

        return response()->json([
            'message' => __('api.follows.unfollowed'),
        ]);
    }

    public function accept(FollowRequest $request, User $user): JsonResponse
    {
        $updated = $request->user()->followers()->updateExistingPivot($user->id, [
            'status' => FollowStatus::Accepted,
        ]);

        return response()->json([
            'message' => $updated ? __('api.follows.accepted') : __('api.follows.not_found'),
        ]);
    }

    public function reject(FollowRequest $request, User $user): JsonResponse
    {
        $detached = $request->user()->followers()->detach($user->id);

        return response()->json([
            'message' => $detached ? __('api.follows.rejected') : __('api.follows.not_found'),
        ]);
    }

    public function followers(Request $request, User $user): AnonymousResourceCollection
    {
        abort_unless($request->user()->id === $user->id, 403);

        $perPage = max(1, min($request->integer('per_page', 15), 100));

        $followers = $user->followers()
            ->wherePivot('status', FollowStatus::Accepted)
            ->paginate($perPage);

        return FollowResource::collection($followers);
    }

    public function following(Request $request, User $user): AnonymousResourceCollection
    {
        abort_unless($request->user()->id === $user->id, 403);

        $perPage = max(1, min($request->integer('per_page', 15), 100));

        $following = $user->following()
            ->wherePivot('status', FollowStatus::Accepted)
            ->paginate($perPage);

        return FollowResource::collection($following);
    }
}
