<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Announcement;
use App\Models\AppNotification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    /**
     * GET /api/notifications
     * Returns the 30 most recent notifications for the authenticated user.
     * Pass ?unread_only=1 to filter to only unread.
     */
    public function index(Request $request): JsonResponse
    {
        $query = AppNotification::where('user_id', $request->user()->id)
            ->where('organization_id', app('current_organization_id'))
            ->orderByDesc('created_at');

        if ($request->boolean('unread_only')) {
            $query->whereNull('read_at');
        }

        $notifications = $query->limit(30)->get()->map(fn ($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(),
        ]);

        return response()->json(['data' => $notifications]);
    }

    /**
     * GET /api/notifications/unread-count
     * Lightweight endpoint polled by the frontend bell every 30 s.
     */
    public function unreadCount(Request $request): JsonResponse
    {
        $count = AppNotification::where('user_id', $request->user()->id)
            ->where('organization_id', app('current_organization_id'))
            ->whereNull('read_at')
            ->count();

        return response()->json(['count' => $count]);
    }

    /**
     * PATCH /api/notifications/{notification}/read
     * Mark a single notification as read. Authorisation: must belong to caller.
     */
    public function markRead(Request $request, AppNotification $notification): JsonResponse
    {
        if ($notification->user_id !== $request->user()->id) {
            return response()->json(['message' => 'Not found.'], 404);
        }

        $notification->markAsRead();

        return response()->json(['message' => 'Marked as read.']);
    }

    /**
     * POST /api/notifications/mark-all-read
     * Mark every unread notification for the caller as read.
     */
    public function markAllRead(Request $request): JsonResponse
    {
        AppNotification::where('user_id', $request->user()->id)
            ->where('organization_id', app('current_organization_id'))
            ->whereNull('read_at')
            ->update(['read_at' => now()]);

        return response()->json(['message' => 'All notifications marked as read.']);
    }

    /**
     * GET /api/announcements/active
     * Returns currently active, non-expired platform announcements that are
     * targeted at the authenticated organisation's subscription plan.
     */
    public function activeAnnouncements(Request $request): JsonResponse
    {
        $org  = $request->user()->organization;
        $plan = 'free';

        if ($org?->subscription && in_array($org->subscription->status, ['active', 'trial'], true)) {
            $plan = $org->subscription->plan;
        }

        $announcements = Announcement::active()
            ->where(fn ($q) => $q->where('audience', 'all')->orWhere('audience', $plan))
            ->orderByDesc('published_at')
            ->get(['id', 'title', 'body', 'type', 'published_at']);

        return response()->json($announcements);
    }
}
