<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

return new class extends Migration
{
    private const TENANT_CODE = 'desfile_pura_tendencia';

    private const FILENAME = 'desfile_pura_tendencia_footer_background.png';

    public function up(): void
    {
        $tenant = DB::table('tenants')
            ->where('codigo', self::TENANT_CODE)
            ->first(['id', 'footer_bg_image_id']);

        if ($tenant === null || $tenant->footer_bg_image_id !== null) {
            return;
        }

        $sourcePath = public_path(
            'images/tennants/desfile_pura_tendencia/'.self::FILENAME
        );

        if (! is_file($sourcePath)) {
            throw new RuntimeException("Image not found at path: {$sourcePath}");
        }

        $contents = file_get_contents($sourcePath);

        if ($contents === false) {
            throw new RuntimeException("Could not read image at path: {$sourcePath}");
        }

        $key = (string) Str::uuid();
        $storedPath = 'tenants/'.self::TENANT_CODE.'/'.$key.'.png';

        if (! Storage::disk('s3')->put($storedPath, $contents)) {
            throw new RuntimeException("Could not store image at path: {$storedPath}");
        }

        try {
            DB::transaction(function () use ($contents, $key, $storedPath): void {
                $attachmentId = DB::table('attachments')->insertGetId([
                    'key' => $key,
                    'path' => $storedPath,
                    'filename' => self::FILENAME,
                    'type' => 'image',
                    'mime_type' => 'image/png',
                    'extension' => 'png',
                    'size' => strlen($contents),
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                DB::table('tenants')
                    ->where('codigo', self::TENANT_CODE)
                    ->update([
                        'footer_bg_image_id' => $attachmentId,
                        'updated_at' => now(),
                    ]);
            });
        } catch (Throwable $throwable) {
            Storage::disk('s3')->delete($storedPath);

            throw $throwable;
        }
    }

    public function down(): void
    {
        // The attachment may already be referenced externally; keep this data
        // migration irreversible instead of deleting a potentially active asset.
    }
};
