<?php

namespace App\Http\Controllers\Api;

use App\Core\Http\Controllers\BaseApiController;
use App\Models\WorkspaceFolder;
use App\Models\WorkspaceItem;
use App\Services\Subscriptions\AiQuotaService;
use App\Services\Subscriptions\PlanCapabilities;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * AI Studio — مساحة عمل (مجلدات + عناصر).
 */
class WorkspaceController extends BaseApiController
{
    public function __construct(
        private readonly AiQuotaService $quota,
    ) {}

    public function folders(Request $request): JsonResponse
    {
        if ($deny = $this->workspaceDenied($request)) {
            return $deny;
        }
        $user = $request->user();
        $folders = WorkspaceFolder::query()
            ->where('user_id', $user->id)
            ->orderBy('name')
            ->limit(200)
            ->get()
            ->map(static fn (WorkspaceFolder $f) => [
                'id' => $f->id,
                'name' => $f->name,
                'parent_id' => $f->parent_id,
            ])->all();

        return $this->successResponse('OK', ['folders' => $folders]);
    }

    public function storeFolder(Request $request): JsonResponse
    {
        if ($deny = $this->workspaceDenied($request)) {
            return $deny;
        }
        $user = $request->user();
        $data = $request->validate([
            'name' => ['required', 'string', 'max:160'],
            'parent_id' => ['nullable', 'integer', 'exists:workspace_folders,id'],
        ]);

        if (! empty($data['parent_id'])) {
            WorkspaceFolder::query()->where('user_id', $user->id)->whereKey($data['parent_id'])->firstOrFail();
        }

        $folder = WorkspaceFolder::query()->create([
            'user_id' => $user->id,
            'name' => $data['name'],
            'parent_id' => $data['parent_id'] ?? null,
        ]);

        return $this->successResponse('تم إنشاء المجلد', ['folder' => ['id' => $folder->id, 'name' => $folder->name]], 201);
    }

    public function items(Request $request): JsonResponse
    {
        if ($deny = $this->workspaceDenied($request)) {
            return $deny;
        }
        $user = $request->user();
        $folderId = $request->query('folder_id');

        $q = WorkspaceItem::query()->where('user_id', $user->id)->orderByDesc('id');
        if ($folderId !== null && $folderId !== '') {
            $q->where('folder_id', (int) $folderId);
        }

        $page = max(1, (int) $request->query('page', 1));
        $per = min(50, max(5, (int) $request->query('per_page', 20)));
        $total = (clone $q)->count();
        $rows = $q->forPage($page, $per)->get();

        $items = $rows->map(static fn (WorkspaceItem $i) => [
            'id' => $i->id,
            'folder_id' => $i->folder_id,
            'type' => $i->type,
            'ref_id' => $i->ref_id,
            'title' => $i->title,
            'meta' => $i->meta,
            'created_at' => $i->created_at?->toIso8601String(),
        ])->all();

        $lastPage = max(1, (int) ceil($total / $per));

        return $this->successResponse('OK', [
            'items' => $items,
            'meta' => [
                'current_page' => $page,
                'per_page' => $per,
                'total' => $total,
                'last_page' => $lastPage,
                'has_more' => $page < $lastPage,
            ],
        ]);
    }

    public function storeItem(Request $request): JsonResponse
    {
        if ($deny = $this->workspaceDenied($request)) {
            return $deny;
        }
        $user = $request->user();
        $data = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'type' => ['required', 'string', 'max:32'],
            'ref_id' => ['nullable', 'integer'],
            'folder_id' => ['nullable', 'integer', 'exists:workspace_folders,id'],
        ]);

        if (! empty($data['folder_id'])) {
            WorkspaceFolder::query()->where('user_id', $user->id)->whereKey($data['folder_id'])->firstOrFail();
        }

        $item = WorkspaceItem::query()->create([
            'user_id' => $user->id,
            'folder_id' => $data['folder_id'] ?? null,
            'type' => $data['type'],
            'ref_id' => $data['ref_id'] ?? null,
            'title' => $data['title'],
            'meta' => [],
        ]);

        return $this->successResponse('تم الحفظ', ['item' => ['id' => $item->id]], 201);
    }

    private function workspaceDenied(Request $request): ?JsonResponse
    {
        $user = $request->user();
        $plan = $this->quota->resolveEffectivePlan($user);
        if (empty(PlanCapabilities::forPlan($plan)['ai_workspace'])) {
            return $this->errorResponse('مساحة العمل متاحة للمشتركين.', ['code' => 'ai_workspace_locked'], 403);
        }

        return null;
    }
}
