<?php

namespace Tests\Unit\Services;

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

class OccupopTest extends TenantTestCase
{
    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(function ($message) {
                return str_contains($message, 'Failed to fetch jobs from Occupop');
            }));

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

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

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