<?php
namespace boru\ai\Tests\Provider\OpenAI;

use boru\ai\Asset\Asset;
use boru\ai\Asset\ProviderAssetBinding;
use boru\ai\Provider\OpenAI\OpenAIAssetProvider;
use boru\ai\Tests\Fakes\FakeOpenAIClient;
use PHPUnit\Framework\TestCase;

class OpenAIAssetProviderTest extends TestCase
{
    public function testEnsureBindingReturnsExistingBindingWhenProviderAssetAlreadyExists()
    {
        $client = new FakeOpenAIClient();
        $provider = new OpenAIAssetProvider($client);

        $asset = new Asset();
        $asset->id('asset_1')->path(__FILE__)->filename('test.php')->mimeType('text/plain');

        $existing = new ProviderAssetBinding();
        $existing->assetId('asset_1')->provider('openai')->providerAssetId('file_existing')->purpose('vision');

        $binding = $provider->ensureBinding($asset, 'vision', $existing);

        $this->assertSame('file_existing', $binding->providerAssetId());
        $this->assertCount(0, $client->requests);
    }

    public function testEnsureBindingUploadsFileAndBuildsProviderBinding()
    {
        $client = new FakeOpenAIClient();
        $client->queueResponse(array(
            'id' => 'file_123',
            'object' => 'file',
            'filename' => 'sample.txt',
        ));

        $provider = new OpenAIAssetProvider($client);
        $asset = new Asset();
        $asset->id('asset_2')->path(__FILE__)->filename('sample.txt')->mimeType('text/plain');

        $binding = $provider->ensureBinding($asset, 'assistants');

        $this->assertSame('asset_2', $binding->assetId());
        $this->assertSame('openai', $binding->provider());
        $this->assertSame('file_123', $binding->providerAssetId());
        $this->assertSame('assistants', $binding->purpose());
        $this->assertSame('ready', $binding->status());
    }

    public function testEnsureBindingKeepsExtensionResolvedOfficeMimeType()
    {
        $tmp = tempnam(sys_get_temp_dir(), 'openai_asset_');
        file_put_contents($tmp, 'xlsx payload');

        $client = new FakeOpenAIClient();
        $client->queueResponse(array(
            'id' => 'file_xlsx',
            'object' => 'file',
            'filename' => 'spreadsheet.xlsx',
        ));

        $provider = new OpenAIAssetProvider($client);
        $asset = new Asset();
        $asset->id('asset_xlsx')
            ->path($tmp)
            ->filename('spreadsheet.xlsx')
            ->mimeType(\boru\ai\Asset\MimeTypeResolver::detect('spreadsheet.xlsx'));

        $binding = $provider->ensureBinding($asset, 'user_data');

        $this->assertSame('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', $client->requests[0]['options']['mime_type']);
        $this->assertSame('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', $binding->mimeType());

        @unlink($tmp);
    }
}
