<?php

declare(strict_types=1);

use App\Models\Artwork;

function encodeLegacyPhotoId(int $value, string $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'): string
{
    if ($value === 0) {
        return '0';
    }

    $encoded = '';

    while ($value > 0) {
        $encoded = $chars[$value % 62] . $encoded;
        $value = intdiv($value, 62);
    }

    return $encoded;
}

it('redirects legacy photo thumbnail urls to the mapped CDN thumbnail size', function (): void {
    config([
        'cdn.files_url' => 'https://cdn.example.test',
        'uploads.object_storage.prefix' => 'artworks',
    ]);

    $artwork = Artwork::factory()->create([
        'hash' => 'aabbccddeeff0011',
        'thumb_ext' => 'webp',
        'file_ext' => 'jpg',
        'file_path' => '',
    ]);

    $response = $this->get('/photo/' . encodeLegacyPhotoId($artwork->id) . '_6.png');

    $response
        ->assertStatus(301)
        ->assertRedirect('https://cdn.example.test/artworks/md/aa/bb/aabbccddeeff0011.webp');
});

it('redirects legacy full-size photo urls to the original CDN asset', function (): void {
    config([
        'cdn.files_url' => 'https://cdn.example.test',
        'uploads.object_storage.prefix' => 'artworks',
    ]);

    $artwork = Artwork::factory()->create([
        'hash' => '1122334455667788',
        'thumb_ext' => 'webp',
        'file_ext' => 'png',
        'file_path' => '',
    ]);

    $response = $this->get('/photo/' . encodeLegacyPhotoId($artwork->id) . '_7.png');

    $response
        ->assertStatus(301)
        ->assertRedirect('https://cdn.example.test/artworks/original/11/22/1122334455667788.png');
});