<?php

namespace Tests\Feature\Api\Tenant;

use App\Enums\TenantAnnouncementAudience;
use App\Enums\TenantAnnouncementSegment;
use App\Enums\TenantAnnouncementStatus;
use App\Models\Tenant;
use App\Models\TenantAnnouncement;
use App\Models\TenantPackage;
use Tests\Feature\Tenant\TenantTestCase;

class TenantAnnouncementsTest extends TenantTestCase
{
    public function test_announcements_endpoint_returns_targeted_active_announcements(): void
    {
        $otherTenant = Tenant::factory()->create();

        $activeAll = TenantAnnouncement::factory()->create([
            'status' => TenantAnnouncementStatus::ACTIVE,
            'audience' => TenantAnnouncementAudience::ALL,
        ]);

        $targeted = TenantAnnouncement::factory()->create([
            'status' => TenantAnnouncementStatus::ACTIVE,
            'audience' => TenantAnnouncementAudience::TENANTS,
        ]);
        $targeted->tenants()->attach($this->tenant->id);

        $segmentActive = TenantAnnouncement::factory()->create([
            'status' => TenantAnnouncementStatus::ACTIVE,
            'audience' => TenantAnnouncementAudience::SEGMENTS,
            'segments' => [TenantAnnouncementSegment::ACTIVE_STATUS->value],
        ]);

        $segmentPackage = TenantAnnouncement::factory()->create([
            'status' => TenantAnnouncementStatus::ACTIVE,
            'audience' => TenantAnnouncementAudience::SEGMENTS,
            'segments' => [TenantAnnouncementSegment::ACTIVE_PACKAGE->value],
        ]);

        TenantPackage::factory()->for($this->tenant)->create(['active' => true]);

        $otherTargeted = TenantAnnouncement::factory()->create([
            'status' => TenantAnnouncementStatus::ACTIVE,
            'audience' => TenantAnnouncementAudience::TENANTS,
        ]);
        $otherTargeted->tenants()->attach($otherTenant->id);

        $draft = TenantAnnouncement::factory()->create([
            'status' => TenantAnnouncementStatus::DRAFT,
            'audience' => TenantAnnouncementAudience::ALL,
        ]);

        $response = $this->authenticatedRequest('GET', '/api/v1/tenant/announcements');

        $response->assertOk();

        $ids = collect($response->json('data'))->pluck('id');

        $this->assertTrue($ids->contains($activeAll->id));
        $this->assertTrue($ids->contains($targeted->id));
        $this->assertTrue($ids->contains($segmentActive->id));
        $this->assertTrue($ids->contains($segmentPackage->id));
        $this->assertFalse($ids->contains($otherTargeted->id));
        $this->assertFalse($ids->contains($draft->id));
    }
}
