<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\BacklogItemResource;
use App\Http\Resources\MeetingResource;
use App\Http\Resources\ProjectResource;
use App\Http\Resources\TaskResource;
use App\Http\Resources\UserResource;
use App\Models\BacklogItem;
use App\Models\User;
use App\Services\ResourceAccessService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function __construct(private readonly ResourceAccessService $resourceAccess) {}

    public function search(Request $request): JsonResponse
    {
        try {
            $request->validate(['q' => 'required|string|min:2']);
            $keyword = $request->q;
            $limit = $request->input('limit', 5);

            $projects = $this->resourceAccess->projects($request->user())
                ->where('title', 'like', "%{$keyword}%")->limit($limit)->get();
            $tasks = $this->resourceAccess->tasks($request->user())
                ->where('title', 'like', "%{$keyword}%")->limit($limit)->get();
            $meetings = $this->resourceAccess->meetings($request->user())
                ->where('title', 'like', "%{$keyword}%")->limit($limit)->get();
            $backlogItems = BacklogItem::where('title', 'like', "%{$keyword}%")
                ->where(function ($query) use ($request) {
                    $query->whereNull('project_id')
                        ->orWhereIn('project_id', $this->resourceAccess->projects($request->user())->select('projects.id'));
                })->limit($limit)->get();
            $canViewTeam = $request->user()->loadMissing('roles.permissions')->roles->contains('name', 'admin')
                || $request->user()->hasPermission('team.view');
            $users = $canViewTeam
                ? User::where(function ($query) use ($keyword) {
                    $query->where('name', 'like', "%{$keyword}%")
                        ->orWhere('email', 'like', "%{$keyword}%");
                })->limit($limit)->get()
                : collect();

            return response()->json([
                'success' => true,
                'data' => [
                    'projects' => ProjectResource::collection($projects),
                    'tasks' => TaskResource::collection($tasks),
                    'users' => UserResource::collection($users),
                    'meetings' => MeetingResource::collection($meetings),
                    'backlog_items' => BacklogItemResource::collection($backlogItems),
                ],
                'message' => 'نتایج جستجو',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در جستجو',
            ], 500);
        }
    }
}
