<?php

namespace App\Http\Controllers\Api;

use App\Core\Http\Controllers\BaseApiController;
use App\Models\UserFeedback;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * تقارير الأخطاء، الملاحظات، وتقييم التجربة.
 */
class UserFeedbackController extends BaseApiController
{
    public function store(Request $request): JsonResponse
    {
        $user = $request->user();

        $data = $request->validate([
            'type' => ['required', 'string', 'in:bug,feedback,rating'],
            'subject' => ['nullable', 'string', 'max:255'],
            'body' => ['nullable', 'string', 'max:8000'],
            'rating' => ['nullable', 'integer', 'min:1', 'max:5'],
            'app_version' => ['nullable', 'string', 'max:64'],
            'platform' => ['nullable', 'string', 'max:32'],
        ]);

        if ($data['type'] === UserFeedback::TYPE_RATING && empty($data['rating'])) {
            return $this->errorResponse('يرجى إرسال تقييم بين 1 و 5.', ['code' => 'rating_required'], 422);
        }

        if (in_array($data['type'], [UserFeedback::TYPE_BUG, UserFeedback::TYPE_FEEDBACK], true)
            && (empty($data['body']) || trim((string) $data['body']) === '')) {
            return $this->errorResponse('يرجى كتابة وصف للرسالة.', ['code' => 'body_required'], 422);
        }

        UserFeedback::query()->create([
            'user_id' => $user->id,
            'type' => $data['type'],
            'subject' => $data['subject'] ?? null,
            'body' => $data['body'] ?? null,
            'rating' => $data['rating'] ?? null,
            'app_version' => $data['app_version'] ?? null,
            'platform' => $data['platform'] ?? null,
            'meta' => [
                'ip' => $request->ip(),
                'user_agent' => mb_substr((string) $request->userAgent(), 0, 500),
            ],
        ]);

        return $this->successResponse('شكراً — تم استلام رسالتك.', ['saved' => true], 201);
    }
}
