<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreCommentRequest;
use App\Http\Resources\CommentResource;
use App\Models\Comment;
use App\Models\Meeting;
use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use App\Services\ActivityLogService;
use App\Services\NotificationService;
use App\Services\ResourceAccessService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CommentController extends Controller
{
    public function __construct(
        protected ActivityLogService $activityLogService,
        protected NotificationService $notificationService,
        protected ResourceAccessService $resourceAccess,
    ) {}

    public function index(Request $request): JsonResponse
    {
        try {
            $query = $this->resourceAccess->comments($request->user())->with(['user', 'files']);

            if ($request->filled('commentable_type')) {
                $query->where('commentable_type', $request->commentable_type);
            }
            if ($request->filled('commentable_id')) {
                $query->where('commentable_id', $request->commentable_id);
            }

            $perPage = $request->input('per_page', 15);
            $comments = $query->orderBy('created_at', 'desc')->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => CommentResource::collection($comments),
                'meta' => [
                    'current_page' => $comments->currentPage(),
                    'last_page' => $comments->lastPage(),
                    'per_page' => $comments->perPage(),
                    'total' => $comments->total(),
                ],
                'message' => 'لیست نظرات',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت نظرات',
            ], 500);
        }
    }

    public function store(StoreCommentRequest $request): JsonResponse
    {
        try {
            $data = $request->validated();
            $allowed = match ($data['commentable_type']) {
                Project::class => $this->resourceAccess->projects($request->user())->whereKey($data['commentable_id'])->exists(),
                Task::class => $this->resourceAccess->tasks($request->user())->whereKey($data['commentable_id'])->exists(),
                Meeting::class => $this->resourceAccess->meetings($request->user())->whereKey($data['commentable_id'])->exists(),
                default => false,
            };
            abort_unless($allowed, 403, 'شما به محل انتخاب‌شده برای نظر دسترسی ندارید.');
            $data['user_id'] = $request->user()->id;
            $comment = Comment::create($data);
            $comment->load('user');

            if (! empty($data['mentioned_user_id'])) {
                $mentionedUser = User::find($data['mentioned_user_id']);
                if ($mentionedUser && $mentionedUser->id !== $request->user()->id) {
                    $this->notificationService->create(
                        $mentionedUser->id,
                        'mention',
                        [
                            'comment_id' => $comment->id,
                            'task_id' => $comment->commentable_type === 'App\\Models\\Task' ? $comment->commentable_id : null,
                            'notifiable_type' => $comment->commentable_type,
                            'notifiable_id' => $comment->commentable_id,
                            'url' => $comment->commentable_type === 'App\\Models\\Task' ? '/kanban' : null,
                        ],
                        "شما توسط {$request->user()->name} در یک نوت منشن شدید"
                    );
                }
            }

            preg_match_all('/@(\w+)/', $comment->body, $matches);
            if (! empty($matches[1])) {
                $mentionedUsers = User::whereIn('name', $matches[1])->get();
                foreach ($mentionedUsers as $mentionedUser) {
                    $mentionedUser->notifications()->create([
                        'type' => 'mention',
                        'title' => 'منشن جدید',
                        'body' => "شما در کامنت توسط {$request->user()->name} منشن شدید",
                        'data' => [
                            'comment_id' => $comment->id,
                            'task_id' => $comment->commentable_type === 'App\\Models\\Task' ? $comment->commentable_id : null,
                            'url' => $comment->commentable_type === 'App\\Models\\Task' ? '/kanban' : null,
                        ],
                        'is_read' => false,
                    ]);
                }
            }

            $this->activityLogService->log(
                $request->user()->id,
                'create_comment',
                'نظر جدید اضافه شد',
                $comment->commentable_type,
                $comment->commentable_id,
                null,
                null,
                ['comment_id' => $comment->id]
            );

            return response()->json([
                'success' => true,
                'data' => new CommentResource($comment),
                'message' => 'نظر با موفقیت ثبت شد',
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در ثبت نظر',
            ], 500);
        }
    }

    public function update(Request $request, Comment $comment): JsonResponse
    {
        try {
            if ($comment->user_id !== $request->user()->id) {
                return response()->json([
                    'success' => false,
                    'message' => 'شما اجازه ویرایش این نظر را ندارید',
                ], 403);
            }

            $request->validate(['body' => 'required|string']);
            $comment->update(['body' => $request->body]);

            return response()->json([
                'success' => true,
                'data' => new CommentResource($comment->fresh()->load('user')),
                'message' => 'نظر به‌روزرسانی شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در به‌روزرسانی نظر',
            ], 500);
        }
    }

    public function destroy(Request $request, Comment $comment): JsonResponse
    {
        try {
            if ($comment->user_id !== $request->user()->id) {
                return response()->json([
                    'success' => false,
                    'message' => 'شما اجازه حذف این نظر را ندارید',
                ], 403);
            }

            $comment->delete();

            return response()->json([
                'success' => true,
                'message' => 'نظر حذف شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در حذف نظر',
            ], 500);
        }
    }
}
