<?php

namespace App\Http\Controllers;

use App\Enums\QrRenderFormat;
use App\Models\QrCode;
use App\Services\QrCode\QrImageRenderer;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

/**
 * Admin-only QR code image endpoints: download (as an attachment) and
 * preview (inline, for the admin UI).
 */
class QrCodeImageController extends Controller
{
    public function __construct(private readonly QrImageRenderer $renderer)
    {
        //
    }

    /**
     * Serve the rendered QR image as a download attachment.
     */
    public function __invoke(Request $request, QrCode $qrCode, QrRenderFormat $format): Response
    {
        $rendered = $this->renderer->render($qrCode, $format, ipAddress: $request->ip());

        return response($rendered['bytes'], 200, [
            'Content-Type' => $rendered['mimeType'],
            'Content-Disposition' => sprintf(
                'attachment; filename="%s.%s"',
                $qrCode->short_code,
                $format->extension(),
            ),
        ]);
    }

    /**
     * Serve the rendered QR image inline, for the admin UI to embed.
     */
    public function preview(Request $request, QrCode $qrCode): Response
    {
        $rendered = $this->renderer->render($qrCode, QrRenderFormat::Png, ipAddress: $request->ip());

        return response($rendered['bytes'], 200, [
            'Content-Type' => $rendered['mimeType'],
            'Content-Disposition' => 'inline',
        ]);
    }
}
