<?php

namespace App\Http\Controllers\Api\V1;

use App\Exceptions\DomainException;
use App\Http\Controllers\Controller;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Notifications\DatabaseNotification;

class NotificationController extends Controller
{
    use ApiResponse;

    public function index(Request $request)
    {
        $paginator = $request->user()->notifications()
            ->orderByDesc('created_at')
            ->paginate(min(100, max(1, $request->integer('per_page', 20))));

        $data = $paginator->getCollection()->map(fn ($notification) => [
            'id' => $notification->id,
            'type' => $notification->type,
            'data' => $notification->data,
            'read_at' => $notification->read_at?->toIso8601String(),
            'created_at' => $notification->created_at?->toIso8601String(),
        ]);

        return $this->paginated($paginator, $data);
    }

    public function read(Request $request, string $notification)
    {
        /** @var DatabaseNotification|null $record */
        $record = $request->user()->notifications()->whereKey($notification)->first();

        if (! $record) {
            throw new DomainException('NOT_FOUND', 'Notification not found.', 404);
        }

        $record->markAsRead();

        return $this->success([
            'id' => $record->id,
            'read_at' => $record->fresh()->read_at?->toIso8601String(),
        ], 'Notification marked as read.');
    }
}
