<?php

namespace Tests\Feature\Authorization;

use App\Models\Filiale;
use App\Models\Form;
use App\Models\FormSubmission;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Gate;
use Tests\TestCase;

class FormSubmissionPolicyTest extends TestCase
{
    use RefreshDatabase;

    public function test_admin_can_view_submission_detail(): void
    {
        [$admin, $submission] = $this->createSubmissionFixture();

        $response = $this->actingAs($admin)
            ->get(route('admin.submissions.show', $submission));

        $response->assertOk();
    }

    public function test_filiale_can_view_own_submission_via_gate(): void
    {
        [, $submission, $filialeUser] = $this->createSubmissionFixture(withFilialeUser: true);

        $this->assertTrue(
            Gate::forUser($filialeUser)->allows('view', $submission)
        );
    }

    public function test_filiale_cannot_view_other_filiale_submission_via_gate(): void
    {
        [, $submission] = $this->createSubmissionFixture(withFilialeUser: true);

        $otherFiliale = Filiale::create([
            'name' => 'Autre filiale',
            'code' => 'FIL-OTHER',
            'is_active' => true,
        ]);

        $otherUser = User::factory()->create([
            'role' => 'filiale',
            'filiale_id' => $otherFiliale->id,
        ]);

        $this->assertFalse(
            Gate::forUser($otherUser)->allows('view', $submission)
        );
    }

    /**
     * @return array{0: User, 1: FormSubmission, 2?: User}
     */
    private function createSubmissionFixture(bool $withFilialeUser = false): array
    {
        $admin = User::factory()->create(['role' => 'admin']);

        $filiale = Filiale::create([
            'name' => 'Filiale test',
            'code' => 'FIL-TEST',
            'is_active' => true,
        ]);

        $filialeUser = User::factory()->create([
            'role' => 'filiale',
            'filiale_id' => $filiale->id,
        ]);

        $form = Form::create([
            'title' => 'Formulaire test',
            'description' => null,
            'created_by' => $admin->id,
            'is_active' => true,
        ]);

        $form->filiales()->attach($filiale->id, ['status' => 'submitted']);

        $submission = FormSubmission::create([
            'form_id' => $form->id,
            'filiale_id' => $filiale->id,
            'user_id' => $filialeUser->id,
            'submitted_at' => now(),
        ]);

        if ($withFilialeUser) {
            return [$admin, $submission, $filialeUser];
        }

        return [$admin, $submission];
    }
}
