<?php

namespace Tests\Feature\Tenant;

use App\Services\Paddle\Exceptions\PaddleException;
use App\Services\Paddle\PaddleCustomerPortalService;
use App\Services\Paddle\PaddleCustomerService;
use Illuminate\Support\Facades\Log;
use Mockery;

class TenantBillingPortalTest extends TenantTestCase
{
    protected function tearDown(): void
    {
        Mockery::close();

        parent::tearDown();
    }

    public function test_portal_logs_paddle_error_context(): void
    {
        $logged = [];
        Log::listen(function ($event) use (&$logged): void {
            $logged[] = [
                'level' => $event->level,
                'message' => $event->message,
                'context' => $event->context,
            ];
        });

        $customerService = Mockery::mock(PaddleCustomerService::class);
        $customerService->shouldReceive('ensureCustomerId')
            ->once()
            ->withArgs(fn ($tenant) => $tenant->is($this->tenant))
            ->andReturn('ctm_test_123');
        $this->instance(PaddleCustomerService::class, $customerService);

        $portalService = Mockery::mock(PaddleCustomerPortalService::class);
        $portalService->shouldReceive('createSession')
            ->once()
            ->with('ctm_test_123')
            ->andThrow(new PaddleException('Paddle request failed with status 404', 404, [
                'error' => [
                    'code' => 'entity_not_found',
                    'message' => 'Not found',
                ],
            ]));
        $this->instance(PaddleCustomerPortalService::class, $portalService);

        $response = $this->authenticatedRequest('POST', '/api/v1/tenant/billing/portal');

        $response->assertStatus(502)
            ->assertJson([
                'message' => 'Failed to create Paddle customer portal session.',
            ]);

        $matched = collect($logged)->contains(function (array $entry): bool {
            return $entry['level'] === 'warning'
                && $entry['message'] === 'Failed to create Paddle customer portal session'
                && ($entry['context']['tenant_id'] ?? null) === $this->tenant->id
                && ($entry['context']['paddle_customer_id'] ?? null) === 'ctm_test_123'
                && ($entry['context']['paddle_status'] ?? null) === 404
                && ($entry['context']['paddle_error_code'] ?? null) === 'entity_not_found';
        });

        $this->assertTrue($matched);
    }
}
