<?php

namespace App\Http\Controllers\Api\Tenant;

use App\Http\Controllers\Controller;
use App\Http\Resources\Tenant\TenantAnnouncementResource;
use App\Models\Tenant;
use App\Services\TenantAnnouncements\TenantAnnouncementService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Arr;

class TenantAnnouncementController extends Controller
{
    public function index(
        Request $request,
        TenantAnnouncementService $service
    ): AnonymousResourceCollection|JsonResponse {
        $tenant = $request->attributes->get('tenant');

        if (! $tenant instanceof Tenant) {
            $decoded = $request->attributes->get('decoded_token', []);
            $tenantId = Arr::get($decoded, 'tenant_id');

            if ($tenantId) {
                $tenant = Tenant::query()->find($tenantId);
            }
        }

        if (! $tenant instanceof Tenant) {
            return response()->json([
                'message' => 'Tenant context missing.',
            ], 401);
        }

        $announcements = $service->visibleAnnouncementsForTenant($tenant);

        return TenantAnnouncementResource::collection($announcements);
    }
}
