<?php

declare(strict_types=1);

namespace Tests\Unit\Endpoint\Api\V1;

use App\Enums\TagMatchType;
use App\Enums\TimeEntryAggregationType;
use App\Enums\TimeEntryRoundingType;
use App\Enums\TimeEntryType;
use App\Enums\Weekday;
use App\Http\Controllers\Api\V1\ReportController;
use App\Models\Client;
use App\Models\Project;
use App\Models\Report;
use App\Models\Tag;
use App\Models\Task;
use App\Service\TimeEntryFilter;
use Illuminate\Support\Carbon;
use Illuminate\Testing\Fluent\AssertableJson;
use Laravel\Passport\Passport;
use PHPUnit\Framework\Attributes\UsesClass;

#[UsesClass(ReportController::class)]
class ReportEndpointTest extends ApiEndpointTestAbstract
{
    public function test_index_endpoint_fails_if_user_does_not_have_permission_to_view_reports(): void
    {
        // Arrange
        $data = $this->createUserWithPermission();
        Report::factory()->forOrganization($data->organization)->createMany(4);
        Passport::actingAs($data->user);

        // Act
        $response = $this->getJson(route('api.v1.reports.index', ['organization' => $data->organization->getKey()]));

        // Assert
        $response->assertForbidden();
    }

    public function test_index_endpoint_returns_list_of_all_reports_of_organization_ordered_by_created_at_desc_per_default(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:view',
        ]);
        Report::factory()->forOrganization($data->organization)->randomCreatedAt()->createMany(4);
        Passport::actingAs($data->user);

        // Act
        $response = $this->getJson(route('api.v1.reports.index', [$data->organization->getKey()]));

        // Assert
        $response->assertStatus(200);
        $response->assertJsonCount(4, 'data');
        $reports = Report::query()->orderBy('created_at', 'desc')->orderBy('id')->get();
        $response->assertJson(fn (AssertableJson $json) => $json
            ->has('data')
            ->has('links')
            ->has('meta')
            ->count('data', 4)
            ->where('data.0.id', $reports->get(0)->getKey())
            ->where('data.1.id', $reports->get(1)->getKey())
            ->where('data.2.id', $reports->get(2)->getKey())
            ->where('data.3.id', $reports->get(3)->getKey())
        );
    }

    public function test_store_endpoint_fails_if_user_has_no_permission_to_create_report(): void
    {
        // Arrange
        $data = $this->createUserWithPermission();
        Passport::actingAs($data->user);

        // Act
        $response = $this->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
            'name' => 'Test Report',
            'is_public' => false,
            'properties' => [
                'group' => TimeEntryAggregationType::Project->value,
                'sub_group' => TimeEntryAggregationType::Task->value,
                'history_group' => TimeEntryAggregationType::Day->value,
                'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
                'end' => Carbon::now()->toIso8601ZuluString(),
            ],
        ]);

        // Assert
        $response->assertForbidden();
    }

    public function test_store_endpoint_creates_new_report_with_minimal_properties(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:create',
        ]);
        Passport::actingAs($data->user);

        // Act
        $response = $this->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
            'name' => 'Test Report',
            'is_public' => false,
            'properties' => [
                'group' => TimeEntryAggregationType::Project->value,
                'sub_group' => TimeEntryAggregationType::Task->value,
                'history_group' => TimeEntryAggregationType::Day->value,
                'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
                'end' => Carbon::now()->toIso8601ZuluString(),
            ],
        ]);

        // Assert
        $response->assertStatus(201);
        $response->assertJson(fn (AssertableJson $json) => $json
            ->has('data')
            ->where('data.name', 'Test Report')
            ->where('data.description', null)
            ->where('data.is_public', false)
            ->where('data.shareable_link', null)
            ->where('data.properties.group', TimeEntryAggregationType::Project->value)
            ->where('data.properties.sub_group', TimeEntryAggregationType::Task->value)
        );
    }

    public function test_store_endpoint_creates_new_report_with_all_properties(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:create',
        ]);
        Passport::actingAs($data->user);

        // Act
        $response = $this->withoutExceptionHandling()->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
            'name' => 'Test Report',
            'description' => 'Test description',
            'is_public' => true,
            'public_until' => Carbon::now()->addDays(30)->toIso8601ZuluString(),
            'properties' => [
                'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
                'end' => Carbon::now()->toIso8601ZuluString(),
                'active' => true,
                'member_ids' => [],
                'billable' => true,
                'client_ids' => [],
                'project_ids' => [],
                'tag_ids' => [],
                'task_ids' => [],
                'group' => TimeEntryAggregationType::Project->value,
                'sub_group' => TimeEntryAggregationType::Task->value,
                'history_group' => TimeEntryAggregationType::Day->value,
                'week_start' => Weekday::Monday->value,
                'timezone' => 'Europe/Berlin',
            ],
        ]);

        // Assert
        $response->assertStatus(201);
        /** @var Report $report */
        $report = Report::query()->findOrFail($response->json('data.id'));
        $response->assertJson(fn (AssertableJson $json) => $json
            ->has('data')
            ->where('data.name', 'Test Report')
            ->where('data.description', 'Test description')
            ->where('data.is_public', true)
            ->where('data.shareable_link', $report->getShareableLink())
            ->where('data.properties.group', TimeEntryAggregationType::Project->value)
            ->where('data.properties.sub_group', TimeEntryAggregationType::Task->value)
        );
    }

    public function test_store_endpoint_creates_new_report_with_rounding_properties(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:create',
        ]);
        Passport::actingAs($data->user);

        // Act
        $response = $this->withoutExceptionHandling()->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
            'name' => 'Test Report with Rounding',
            'description' => 'Test description',
            'is_public' => true,
            'public_until' => Carbon::now()->addDays(30)->toIso8601ZuluString(),
            'properties' => [
                'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
                'end' => Carbon::now()->toIso8601ZuluString(),
                'active' => true,
                'member_ids' => [],
                'billable' => true,
                'client_ids' => [],
                'project_ids' => [],
                'tag_ids' => [],
                'task_ids' => [],
                'group' => TimeEntryAggregationType::Project->value,
                'sub_group' => TimeEntryAggregationType::Task->value,
                'history_group' => TimeEntryAggregationType::Day->value,
                'week_start' => Weekday::Monday->value,
                'timezone' => 'Europe/Berlin',
                'rounding_type' => 'nearest',
                'rounding_minutes' => 15,
            ],
        ]);

        // Assert
        $response->assertStatus(201);
        /** @var Report $report */
        $report = Report::query()->findOrFail($response->json('data.id'));
        $response->assertJson(fn (AssertableJson $json) => $json
            ->has('data')
            ->where('data.name', 'Test Report with Rounding')
            ->where('data.description', 'Test description')
            ->where('data.is_public', true)
            ->where('data.shareable_link', $report->getShareableLink())
            ->where('data.properties.group', TimeEntryAggregationType::Project->value)
            ->where('data.properties.sub_group', TimeEntryAggregationType::Task->value)
            ->where('data.properties.rounding_type', 'nearest')
            ->where('data.properties.rounding_minutes', 15)
        );

        // Also verify the properties are saved in the database
        $this->assertSame(TimeEntryRoundingType::Nearest, $report->properties->roundingType);
        $this->assertSame(15, $report->properties->roundingMinutes);
    }

    public function test_store_endpoint_creates_new_report_with_time_entry_type_filter(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:create',
        ]);
        Passport::actingAs($data->user);

        // Act
        $response = $this->withoutExceptionHandling()->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
            'name' => 'Test Report',
            'is_public' => false,
            'properties' => [
                'group' => TimeEntryAggregationType::Project->value,
                'sub_group' => TimeEntryAggregationType::Task->value,
                'history_group' => TimeEntryAggregationType::Day->value,
                'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
                'end' => Carbon::now()->toIso8601ZuluString(),
                'time_entry_type' => TimeEntryType::Break->value,
            ],
        ]);

        // Assert
        $response->assertStatus(201);
        $response->assertJsonPath(
            'data.properties.time_entry_type',
            TimeEntryType::Break->value
        );
        /** @var Report $report */
        $report = Report::query()->findOrFail($response->json('data.id'));
        $this->assertSame(TimeEntryType::Break, $report->properties->timeEntryType);
    }

    public function test_store_endpoint_fails_if_time_entry_type_is_invalid(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:create',
        ]);
        Passport::actingAs($data->user);

        // Act
        $response = $this->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
            'name' => 'Test Report',
            'is_public' => false,
            'properties' => [
                'group' => TimeEntryAggregationType::Project->value,
                'sub_group' => TimeEntryAggregationType::Task->value,
                'history_group' => TimeEntryAggregationType::Day->value,
                'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
                'end' => Carbon::now()->toIso8601ZuluString(),
                'time_entry_type' => 'invalid-type',
            ],
        ]);

        // Assert
        $response->assertStatus(422);
        $response->assertJsonValidationErrors(['properties.time_entry_type']);
    }

    public function test_update_endpoint_fails_if_user_has_no_permission_to_update_report(): void
    {
        // Arrange
        $data = $this->createUserWithPermission();
        $report = Report::factory()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
            'name' => 'Updated Report',
        ]);

        // Assert
        $response->assertForbidden();
    }

    public function test_update_endpoint_fails_if_report_does_not_exist(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:update',
        ]);
        Passport::actingAs($data->user);

        // Act
        $response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), 1]), [
            'name' => 'Updated Report',
        ]);

        // Assert
        $response->assertNotFound();
    }

    public function test_update_endpoint_fails_if_report_does_not_belong_to_organization(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:update',
        ]);
        $report = Report::factory()->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
            'name' => 'Updated Report',
        ]);

        // Assert
        $response->assertForbidden();
    }

    public function test_update_endpoint_can_update_only_the_name_of_the_report(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:update',
        ]);
        $report = Report::factory()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
            'name' => 'Updated Report',
        ]);

        // Assert
        $report->refresh();
        $this->assertSame('Updated Report', $report->name);
        $response->assertStatus(200);
        $response->assertJson(fn (AssertableJson $json) => $json
            ->has('data')
            ->where('data.name', 'Updated Report')
        );
    }

    public function test_update_endpoint_can_update_only_the_description_of_the_report(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:update',
        ]);
        $report = Report::factory()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
            'description' => 'Updated description',
        ]);

        // Assert
        $report->refresh();
        $this->assertSame('Updated description', $report->description);
        $response->assertStatus(200);
        $response->assertJson(fn (AssertableJson $json) => $json
            ->has('data')
            ->where('data.description', 'Updated description')
        );
    }

    public function test_update_endpoint_can_set_a_report_from_private_to_public_which_generates_a_new_secret(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:update',
        ]);
        $report = Report::factory()->private()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
            'is_public' => true,
        ]);

        // Assert
        $report->refresh();
        $this->assertTrue($report->is_public);
        $this->assertNotNull($report->share_secret);
        $this->assertResponseCode($response, 200);
        $response->assertJson(fn (AssertableJson $json) => $json
            ->has('data')
            ->where('data.is_public', true)
            ->where('data.shareable_link', $report->getShareableLink())
        );
    }

    public function test_update_endpoint_can_set_a_report_from_public_to_private_which_resets_the_secret(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:update',
        ]);
        $report = Report::factory()->public()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
            'is_public' => false,
        ]);

        // Assert
        $report->refresh();
        $this->assertFalse($report->is_public);
        $this->assertNull($report->share_secret);
        $response->assertStatus(200);
        $response->assertJson(fn (AssertableJson $json) => $json
            ->has('data')
            ->where('data.is_public', false)
            ->where('data.shareable_link', null)
        );
    }

    public function test_update_endpoint_does_not_change_the_secret_of_a_public_report_if_it_is_set_to_public_again(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:update',
        ]);
        $report = Report::factory()->public()->forOrganization($data->organization)->create();
        $secret = $report->share_secret;
        Passport::actingAs($data->user);

        // Act
        $response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
            'is_public' => true,
        ]);

        // Assert
        $report->refresh();
        $this->assertTrue($report->is_public);
        $this->assertSame($secret, $report->share_secret);
        $response->assertStatus(200);
        $response->assertJson(fn (AssertableJson $json) => $json
            ->has('data')
            ->where('data.is_public', true)
            ->where('data.shareable_link', $report->getShareableLink())
        );
    }

    public function test_update_endpoint_can_update_the_report_all_properties_set(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:update',
        ]);
        $report = Report::factory()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
            'name' => 'Updated Report',
            'description' => 'Updated description',
            'is_public' => true,
            'public_until' => Carbon::now()->addDays(30)->toIso8601ZuluString(),
        ]);

        // Assert
        $response->assertStatus(200);
        $response->assertJson(fn (AssertableJson $json) => $json
            ->has('data')
            ->where('data.name', 'Updated Report')
            ->where('data.description', 'Updated description')
            ->where('data.is_public', true)
            ->whereType('data.public_until', 'string')
            ->where('data.properties.group', TimeEntryAggregationType::Project->value)
            ->where('data.properties.sub_group', TimeEntryAggregationType::Task->value)
        );
    }

    public function test_update_endpoint_can_update_public_until_on_already_public_report(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:update',
        ]);
        $report = Report::factory()->public()->forOrganization($data->organization)->create([
            'public_until' => null,
        ]);
        Passport::actingAs($data->user);
        $newPublicUntil = Carbon::now()->addDays(30);

        // Act
        $response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
            'public_until' => $newPublicUntil->toIso8601ZuluString(),
        ]);

        // Assert
        $response->assertStatus(200);
        $report->refresh();
        $this->assertTrue($report->is_public);
        $this->assertNotNull($report->public_until);
        $this->assertTrue($newPublicUntil->isSameDay($report->public_until));
    }

    public function test_update_endpoint_can_clear_public_until_on_already_public_report(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:update',
        ]);
        $report = Report::factory()->public()->forOrganization($data->organization)->create([
            'public_until' => Carbon::now()->addDays(30),
        ]);
        Passport::actingAs($data->user);

        // Act
        $response = $this->putJson(route('api.v1.reports.update', [$data->organization->getKey(), $report->getKey()]), [
            'public_until' => null,
        ]);

        // Assert
        $response->assertStatus(200);
        $report->refresh();
        $this->assertTrue($report->is_public);
        $this->assertNull($report->public_until);
    }

    public function test_show_endpoint_fails_if_user_has_no_permission_to_view_report(): void
    {
        // Arrange
        $data = $this->createUserWithPermission();
        $report = Report::factory()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->getJson(route('api.v1.reports.show', [$data->organization->getKey(), $report->getKey()]));

        // Assert
        $response->assertForbidden();
    }

    public function test_show_endpoint_fails_if_report_does_not_exist(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:view',
        ]);
        Passport::actingAs($data->user);

        // Act
        $response = $this->getJson(route('api.v1.reports.show', [$data->organization->getKey(), 1]));

        // Assert
        $response->assertNotFound();
    }

    public function test_show_endpoint_fails_if_report_does_not_belong_to_organization(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:view',
        ]);
        $report = Report::factory()->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->getJson(route('api.v1.reports.show', [$data->organization->getKey(), $report->getKey()]));

        // Assert
        $response->assertForbidden();
    }

    public function test_show_endpoint_returns_detailed_report(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:view',
        ]);
        $report = Report::factory()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->getJson(route('api.v1.reports.show', [$data->organization->getKey(), $report->getKey()]));

        // Assert
        $response->assertStatus(200);
        $response->assertJson(fn (AssertableJson $json) => $json
            ->has('data')
            ->where('data.id', $report->getKey())
        );
    }

    public function test_store_endpoint_creates_report_with_none_filter_values(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:create',
        ]);
        Passport::actingAs($data->user);

        // Act
        $response = $this->withoutExceptionHandling()->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
            'name' => 'Test Report with None Filters',
            'is_public' => false,
            'properties' => [
                'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
                'end' => Carbon::now()->toIso8601ZuluString(),
                'group' => TimeEntryAggregationType::Project->value,
                'sub_group' => TimeEntryAggregationType::Task->value,
                'history_group' => TimeEntryAggregationType::Day->value,
                'project_ids' => [TimeEntryFilter::NONE_VALUE],
                'client_ids' => [TimeEntryFilter::NONE_VALUE],
                'tag_ids' => [TimeEntryFilter::NONE_VALUE],
                'task_ids' => [TimeEntryFilter::NONE_VALUE],
            ],
        ]);

        // Assert
        $response->assertStatus(201);
        /** @var Report $report */
        $report = Report::query()->findOrFail($response->json('data.id'));
        $this->assertTrue($report->properties->projectIds->contains(TimeEntryFilter::NONE_VALUE));
        $this->assertTrue($report->properties->clientIds->contains(TimeEntryFilter::NONE_VALUE));
        $this->assertTrue($report->properties->tagIds->contains(TimeEntryFilter::NONE_VALUE));
        $this->assertTrue($report->properties->taskIds->contains(TimeEntryFilter::NONE_VALUE));
    }

    public function test_store_endpoint_creates_report_with_none_combined_with_real_ids(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:create',
        ]);
        $project = Project::factory()->forOrganization($data->organization)->create();
        $client = Client::factory()->forOrganization($data->organization)->create();
        $task = Task::factory()->forOrganization($data->organization)->forProject($project)->create();
        $tag = Tag::factory()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->withoutExceptionHandling()->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
            'name' => 'Test Report with Combined Filters',
            'is_public' => false,
            'properties' => [
                'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
                'end' => Carbon::now()->toIso8601ZuluString(),
                'group' => TimeEntryAggregationType::Project->value,
                'sub_group' => TimeEntryAggregationType::Task->value,
                'history_group' => TimeEntryAggregationType::Day->value,
                'project_ids' => [$project->getKey(), TimeEntryFilter::NONE_VALUE],
                'client_ids' => [$client->getKey(), TimeEntryFilter::NONE_VALUE],
                'tag_ids' => [$tag->getKey(), TimeEntryFilter::NONE_VALUE],
                'task_ids' => [$task->getKey(), TimeEntryFilter::NONE_VALUE],
            ],
        ]);

        // Assert
        $response->assertStatus(201);
        /** @var Report $report */
        $report = Report::query()->findOrFail($response->json('data.id'));
        $this->assertTrue($report->properties->projectIds->contains($project->getKey()));
        $this->assertTrue($report->properties->projectIds->contains(TimeEntryFilter::NONE_VALUE));
        $this->assertTrue($report->properties->clientIds->contains($client->getKey()));
        $this->assertTrue($report->properties->clientIds->contains(TimeEntryFilter::NONE_VALUE));
        $this->assertTrue($report->properties->tagIds->contains($tag->getKey()));
        $this->assertTrue($report->properties->tagIds->contains(TimeEntryFilter::NONE_VALUE));
        $this->assertTrue($report->properties->taskIds->contains($task->getKey()));
        $this->assertTrue($report->properties->taskIds->contains(TimeEntryFilter::NONE_VALUE));
    }

    public function test_destroy_endpoint_fails_if_user_has_no_permission_to_delete_report(): void
    {
        // Arrange
        $data = $this->createUserWithPermission();
        $report = Report::factory()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->deleteJson(route('api.v1.reports.destroy', [$data->organization->getKey(), $report->getKey()]));

        // Assert
        $response->assertForbidden();
    }

    public function test_destroy_endpoint_fails_if_report_belongs_to_another_organization(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:delete',
        ]);
        $report = Report::factory()->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->deleteJson(route('api.v1.reports.destroy', [$data->organization->getKey(), $report->getKey()]));

        // Assert
        $response->assertForbidden();
    }

    public function test_destroy_endpoint_fails_if_report_does_not_exist(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:delete',
        ]);
        Passport::actingAs($data->user);

        // Act
        $response = $this->deleteJson(route('api.v1.reports.destroy', [$data->organization->getKey(), 1]));

        // Assert
        $response->assertNotFound();
    }

    public function test_destroy_endpoint_deletes_a_report(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:delete',
        ]);
        $report = Report::factory()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->deleteJson(route('api.v1.reports.destroy', [$data->organization->getKey(), $report->getKey()]));

        // Assert
        $response->assertNoContent();
        $this->assertDatabaseMissing(Report::class, [
            'id' => $report->getKey(),
        ]);
    }

    public function test_store_endpoint_persists_tag_match_type(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:create',
        ]);
        $tag = Tag::factory()->forOrganization($data->organization)->create();
        Passport::actingAs($data->user);

        // Act
        $response = $this->withoutExceptionHandling()->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
            'name' => 'Report with tag match type',
            'is_public' => false,
            'properties' => [
                'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
                'end' => Carbon::now()->toIso8601ZuluString(),
                'group' => TimeEntryAggregationType::Project->value,
                'sub_group' => TimeEntryAggregationType::Task->value,
                'history_group' => TimeEntryAggregationType::Day->value,
                'tag_ids' => [$tag->getKey()],
                'tag_match_type' => TagMatchType::NotContains->value,
            ],
        ]);

        // Assert
        $response->assertStatus(201);
        /** @var Report $report */
        $report = Report::query()->findOrFail($response->json('data.id'));
        $this->assertSame(TagMatchType::NotContains, $report->properties->tagMatchType);
        // DetailedReportResource exposes the match type in the response
        $response->assertJsonPath('data.properties.tag_match_type', TagMatchType::NotContains->value);
    }

    public function test_store_endpoint_rejects_invalid_tag_match_type(): void
    {
        // Arrange
        $data = $this->createUserWithPermission([
            'reports:create',
        ]);
        Passport::actingAs($data->user);

        // Act
        $response = $this->postJson(route('api.v1.reports.store', [$data->organization->getKey()]), [
            'name' => 'Report with invalid tag match type',
            'is_public' => false,
            'properties' => [
                'start' => Carbon::now()->subDays(30)->toIso8601ZuluString(),
                'end' => Carbon::now()->toIso8601ZuluString(),
                'group' => TimeEntryAggregationType::Project->value,
                'sub_group' => TimeEntryAggregationType::Task->value,
                'history_group' => TimeEntryAggregationType::Day->value,
                'tag_match_type' => 'invalid_value',
            ],
        ]);

        // Assert
        $response->assertStatus(422);
        $response->assertInvalid(['properties.tag_match_type']);
    }
}
