<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Bid;
use App\Models\Notification;
use App\Models\User;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (! $user) {
            return ApiResponse::response(message: 'شما وارد سایت نشده اید!', status: 420);
        }

        $unreadNotifications = $user->unreadNotifications;
        $notifications = $request->only_unread ? $unreadNotifications : $user->notifications;

        $user->refresh();

        return ['notifications' => $notifications, 'wallet' => $user->wallet];
    }

    public function update(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (! $user) {
            return ApiResponse::response(message: 'شما وارد سایت نشده اید!', status: 420);
        }

        $notification = $user->notifications()->where('id', $request->notification)->first();

        if (! $notification) {
            return ApiResponse::response(message: 'شما اجازه انجام این کار را ندارید!', status: 420);
        }

        $notification->update([
            'data' => $request->data,
        ]);

        return $notification;
    }

    public function show(Request $request)
    {
        if (Auth::guard('api')->check()) {
            return ApiResponse::response(message: 'اطلاعات وارد شده صحیح نیست', status: 422);
        }
        $user = User::find(Auth::guard('api')->user()->id);

        if (property_exists($request, 'notification') && $request->notification !== null) {
            return $user->unreadNotifications()->where('id', $request->notification)->first()->markAsRead();
        } else {
            return $user->unreadNotifications->markAsRead();
        }
    }

    public function destroy(Request $request, $notification = null)
    {
        $user = Auth::guard('api')->user();
        if (! $user) {
            return ApiResponse::response(message: 'اطلاعات وارد شده صحیح نیست', status: 422);
        }

        return Notification::find($notification)->delete();
    }
}
