<?php

namespace Tests\Tenant\Services;

use App\Facades\Settings;
use App\Services\Occupop;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Mockery;
use Tests\TenantTestCase;

class OccupopTest extends TenantTestCase
{
    #[\Override]
    protected function setUp(): void
    {
        parent::setUp();

        Config::set('services.occupop.endpoint', 'https://api.occupop.example.com/');

        Settings::shouldReceive('get')
            ->with('jobs-occupop-api_key')
            ->andReturn('fake-key');
    }

    public function testGetJobsReturnsJobsArrayWhenSuccessful()
    {
        Http::fake([
            'https://api.occupop.example.com/fake-key?visibility=external&json' => Http::response([
                'jobs' => [
                    ['id' => 1, 'title' => 'Dev'],
                    ['id' => 2, 'title' => 'Designer']
                ],
            ], 200),
        ]);

        $jobs = new Occupop()->getJobs();

        $this->assertIsArray($jobs);
        $this->assertCount(2, $jobs);
        $this->assertEquals('Dev', $jobs[0]['title']);
    }

    public function testGetJobsReturnsEmptyArrayWhenResponseIsEmpty()
    {
        Http::fake([
            '*' => Http::response(['jobs' => []], 200),
        ]);

        $jobs = new Occupop()->getJobs();

        $this->assertIsArray($jobs);
        $this->assertEmpty($jobs);
    }

    public function testGetJobsReturnsEmptyArrayAndLogsWhenRequestFails()
    {
        Log::shouldReceive('warning')
            ->once()
            ->with(Mockery::on(fn ($message) => str_contains((string) $message, 'Failed to fetch jobs from Occupop')));

        Http::fake([
            '*' => Http::response(null, 500),
        ]);

        $jobs = new Occupop()->getJobs();

        $this->assertIsArray($jobs);
        $this->assertEmpty($jobs);
    }
}
