<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\Notification;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    use BaseApiResponse;

    public function index(Request $request)
    {
        $user = auth()->user();

        $all = Notification::query()->latest()->get();

        $now = now();
        foreach ($all as $notification) {
            $user->notifications()->syncWithoutDetaching([
                $notification->id => ['read_at' => $now],
            ]);
        }

        $notifications = $all->map(function ($notification) {
            return [
                'id' => $notification->id,
                'title' => $notification->title,
                'description' => $notification->description,
                'created_at' => $notification->created_at->toIso8601String(),
                'is_read' => true,
            ];
        });

        return $this->success([
            'notifications' => $notifications,
        ]);
    }
}
