<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\Discussion\StoreDiscussionMessageRequest;
use App\Http\Resources\DiscussionMessageResource;
use App\Models\Discussion;
use App\Models\DiscussionMessage;
use App\Support\ApiResponse;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;

class DiscussionMessageController extends Controller
{
    public function store(StoreDiscussionMessageRequest $request, Discussion $discussion)
    {
        Gate::authorize('postMessage', $discussion);

        try {
            DB::beginTransaction();

            $message = DiscussionMessage::create([
                'discussion_id' => $discussion->id,
                'user_id' => $request->user()->id,
                'body' => $request->input('body'),
                'hashtag' => $request->input('hashtag') ?? $discussion->hashtag,
            ]);

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();

            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return ApiResponse::created(
            new DiscussionMessageResource($message->load('user')),
            'پیام با موفقیت ثبت شد.'
        );
    }

    public function destroy(Discussion $discussion, DiscussionMessage $discussionMessage)
    {
        Gate::authorize('deleteMessage', [$discussion, $discussionMessage]);

        if ($discussionMessage->discussion_id !== $discussion->id) {
            return ApiResponse::notFound('پیام در این بحث یافت نشد.');
        }

        $discussionMessage->delete();

        return ApiResponse::success(
            new DiscussionMessageResource($discussionMessage),
            'پیام حذف شد.'
        );
    }
}
