<?php

use App\Enums\ModerationCaseStatus;
use App\Enums\ReportReason;
use App\Enums\UserRole;
use App\Filament\Resources\ModerationCases\Pages\ListModerationCases;
use App\Models\MealPosts;
use App\Models\ModerationCase;
use App\Models\Report;
use App\Models\User;
use Filament\Facades\Filament;
use Filament\Tables\Columns\TextColumn;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function () {
    app()->setLocale('fr');

    Filament::setCurrentPanel(Filament::getPanel('dashboard'));
});

it('exposes moderation cases in filament and hides a reported meal post', function () {
    $moderator = User::factory()->create(['role' => UserRole::MODERATOR]);
    $mealPost = MealPosts::factory()->create();
    $case = ModerationCase::factory()->create([
        'caseable_type' => MealPosts::class,
        'caseable_id' => $mealPost->id,
        'reports_count' => 3,
        'threshold' => 3,
    ]);

    Report::factory()->create([
        'moderation_case_id' => $case->id,
        'reportable_type' => MealPosts::class,
        'reportable_id' => $mealPost->id,
        'reason' => ReportReason::INAPPROPRIATE,
    ]);

    $this->actingAs($moderator);

    Livewire::test(ListModerationCases::class)
        ->assertTableColumnExists(
            'status',
            fn (TextColumn $column): bool => $column->getLabel() === 'Statut',
        )
        ->callTableAction('hideMeal', $case);

    expect($mealPost->fresh()->hidden_at)->not->toBeNull()
        ->and($mealPost->fresh()->hidden_by)->toBe($moderator->id)
        ->and($case->fresh()->status)->toBe(ModerationCaseStatus::REVIEWING);

    Sanctum::actingAs(User::factory()->create());

    $this->getJson("/api/meal-posts/{$mealPost->id}")
        ->assertNotFound();
});

it('suspends a reported user from the moderation table', function () {
    $moderator = User::factory()->create(['role' => UserRole::MODERATOR]);
    $target = User::factory()->create();
    $case = ModerationCase::factory()->create([
        'caseable_type' => User::class,
        'caseable_id' => $target->id,
        'reports_count' => 5,
        'threshold' => 5,
    ]);

    $this->actingAs($moderator);

    Livewire::test(ListModerationCases::class)
        ->callTableAction('suspendUser', $case);

    expect($target->fresh()->suspended_at)->not->toBeNull()
        ->and($target->fresh()->suspended_by)->toBe($moderator->id);

    Sanctum::actingAs($target->fresh());

    $this->postJson('/api/meal-posts', [
        'image_url' => 'https://example.com/meal.jpg',
        'title' => 'Repas suspendu',
        'eaten_at' => '2026-05-22T12:00:00.000Z',
        'type' => \App\Enums\MealPostType::BREAKFAST->value,
    ])->assertForbidden();
});
