<?php

declare(strict_types=1);

namespace App\Support;

use RuntimeException;

final class DemoPropertyPlaceholderImageFactory
{
    /** @var list<array{bg: array{0: int, 1: int, 2: int}, accent: array{0: int, 1: int, 2: int}}> */
    private const VARIANTS = [
        ['bg' => [30, 64, 120], 'accent' => [16, 185, 129]],
        ['bg' => [15, 118, 110], 'accent' => [45, 212, 191]],
        ['bg' => [71, 85, 105], 'accent' => [251, 191, 36]],
    ];

    public static function createTempFile(int $index, string $caption): string
    {
        if (! extension_loaded('gd')) {
            throw new RuntimeException(
                'Extensão PHP GD não disponível. Reconstrua os containers: docker compose build php queue && docker compose up -d'
            );
        }

        $width = 960;
        $height = 720;
        $variant = self::VARIANTS[max(0, ($index - 1) % count(self::VARIANTS))];

        $image = imagecreatetruecolor($width, $height);

        if ($image === false) {
            throw new RuntimeException('Falha ao criar imagem placeholder.');
        }

        $background = imagecolorallocate($image, ...$variant['bg']);
        imagefilledrectangle($image, 0, 0, $width, $height, $background);

        $accent = imagecolorallocate($image, ...$variant['accent']);
        imagefilledrectangle($image, 0, $height - 140, $width, $height, $accent);

        $white = imagecolorallocate($image, 255, 255, 255);
        $dark = imagecolorallocate($image, 15, 23, 42);

        imagestring($image, 5, 36, 36, 'ImovelZapAi', $white);
        imagestring($image, 4, 36, 68, 'Foto demo', $white);

        $captionLine = self::truncateCaption($caption, 42);
        imagestring($image, 5, 36, $height - 100, $captionLine, $dark);

        $path = tempnam(sys_get_temp_dir(), 'demo-property-');
        $jpgPath = $path.'.jpg';

        if ($path !== false && ! rename($path, $jpgPath)) {
            $jpgPath = $path;
        }

        if (! imagejpeg($image, $jpgPath, 88)) {
            imagedestroy($image);

            throw new RuntimeException('Falha ao salvar imagem placeholder.');
        }

        imagedestroy($image);

        return $jpgPath;
    }

    private static function truncateCaption(string $caption, int $maxLength): string
    {
        if (strlen($caption) <= $maxLength) {
            return $caption;
        }

        return substr($caption, 0, $maxLength - 3).'...';
    }
}
