<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Resources\DiscussionParticipantResource;
use App\Models\Discussion;
use App\Models\DiscussionParticipant;
use App\Models\User;
use App\Support\ApiResponse;
use Illuminate\Support\Facades\Gate;

class DiscussionParticipantController extends Controller
{
    public function block(Discussion $discussion, User $user)
    {
        Gate::authorize('block', $discussion);

        if ($user->id === $discussion->created_by) {
            return ApiResponse::badRequest('ایجادکننده بحث قابل بلاک نیست.');
        }

        $participant = DiscussionParticipant::firstOrCreate(
            [
                'discussion_id' => $discussion->id,
                'user_id' => $user->id,
            ],
            ['is_blocked' => false]
        );

        $participant->update(['is_blocked' => true]);

        return ApiResponse::success(
            new DiscussionParticipantResource($participant->load('user')),
            'کاربر از بحث بلاک شد.'
        );
    }

    public function unblock(Discussion $discussion, User $user)
    {
        Gate::authorize('block', $discussion);

        $participant = DiscussionParticipant::query()
            ->where('discussion_id', $discussion->id)
            ->where('user_id', $user->id)
            ->first();

        if (! $participant) {
            return ApiResponse::notFound('شرکت‌کننده یافت نشد.');
        }

        $participant->update(['is_blocked' => false]);

        return ApiResponse::success(
            new DiscussionParticipantResource($participant->load('user')),
            'بلاک کاربر برداشته شد.'
        );
    }
}
