<?php

namespace App\Http\Controllers\Admin\Office;

use App\Http\Controllers\Controller;
use App\Models\Office\Notification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Notification::query()->where('user_id', auth()->id());
        $query->when($request->type, fn($q, $v) => $q->where('type', $v));
        $query->when($request->has('is_read'), fn($q) => $q->where('is_read', $request->boolean('is_read')));

        return $this->paginate($query->latest('created_at')->paginate($request->input('per_page', 15)));
    }

    public function markRead(Notification $notification): JsonResponse
    {
        if ($notification->user_id !== auth()->id()) {
            return $this->error('无权操作', 40003, 403);
        }
        $notification->update(['is_read' => true, 'read_at' => now()]);

        return $this->success($notification);
    }

    public function markAllRead(): JsonResponse
    {
        Notification::query()
            ->where('user_id', auth()->id())
            ->where('is_read', false)
            ->update(['is_read' => true, 'read_at' => now()]);

        return $this->success(null);
    }
}
