<?php

namespace Media\Controllers;

use App\Framework\Attributes\Route;
use App\Framework\Core\PathProvider;
use App\Framework\Http\Headers;
use App\Framework\Http\HttpResponse;
use App\Framework\Http\Method;
use App\Framework\Http\Status;
use App\Framework\Router\Result\FileResult;
use Media\Entities\Image;
use Media\Services\ImageService;

class MediaController
{
    public function __construct(
        private ImageService $imageService,
        private PathProvider $pathProvider,
    ) {}

    #[Route('/media/{path}-{filename}', method: Method::GET)]
    public function serveMedia(string $path, string $filename): FileResult
    {
        $image = $this->imageService->resolveFromUrlId($path);

        $imagePath = $this->pathProvider->resolvePath('storage' . $image->uploadPath . '/' . $filename);

        #debug($imagePath);

        // Prüfen ob Datei existiert
        if (!file_exists($imagePath)) {
            die('oh');
            return $this->notFound();
        }

        // Lese Datei und sende sie zurück
        $content = file_get_contents($imagePath);
        $mimeType = $this->getMimeTypeFromFormat($image->mimeType);

        $headers = new Headers([
            'Content-Type' => $mimeType,
            'Content-Length' => filesize($imagePath),
            'Cache-Control' => 'public, max-age=31536000', // 1 Jahr cachen
            'ETag' => '"' . md5_file($imagePath) . '"',
        ]);

        return new FileResult($imagePath);

        return new HttpResponse(
            Status::OK,
            $headers,
            $content
        );
    }

    private function constructImagePath(Image $image, string $variant, string $format): string
    {
        return $this->pathProvider->resolvePath('storage' . $image->uploadPath . '/' . $variant . '.' . $format);
    }

    private function getMimeTypeFromFormat(string $format): string
    {
        return match ($format) {
            'jpg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
            'webp' => 'image/webp',
            'avif' => 'image/avif',
            default => 'application/octet-stream'
        };
    }

    private function notFound(): HttpResponse
    {
        return new HttpResponse(
            Status::NOT_FOUND,
            new Headers(['Content-Type' => 'text/plain']),
            'Bild nicht gefunden'
        );
    }
}
