<?php

namespace App\Http\Controllers\Api;

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

class InAppNotificationController extends BaseApiController
{
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();
        $perPage = (int) min(50, max(5, (int) $request->query('per_page', 20)));

        $page = InAppNotification::query()
            ->where('user_id', $user->id)
            ->orderByDesc('id')
            ->paginate($perPage);

        $items = collect($page->items())->map(fn (InAppNotification $n) => [
            'id' => $n->id,
            'type' => $n->type,
            'title' => $n->title,
            'body' => $n->body,
            'data' => $n->data,
            'read_at' => $n->read_at?->toIso8601String(),
            'created_at' => $n->created_at?->toIso8601String(),
        ])->values()->all();

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

    public function markRead(Request $request, int $notification): JsonResponse
    {
        $user = $request->user();
        $n = InAppNotification::query()
            ->where('user_id', $user->id)
            ->whereKey($notification)
            ->first();

        if ($n === null) {
            return $this->errorResponse('غير موجود.', [], 404);
        }

        if ($n->read_at === null) {
            $n->read_at = now();
            $n->save();
        }

        return $this->successResponse('OK', ['id' => $n->id, 'read_at' => $n->read_at->toIso8601String()]);
    }
}
