<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;

class MediaController extends BaseController
{
    public function serve(): void
    {
        $type = $this->getRouteParam('type');
        $filename = $this->getRouteParam('filename');

        $subDir = match($type) {
            'audio' => 'uploads/audio',
            'tasks' => 'uploads/tasks',
            default => 'uploads',
        };
        $filePath = STORAGE_PATH . '/' . $subDir . '/' . basename($filename);

        if (!file_exists($filePath)) {
            Response::error('Archivo no encontrado', 404);
            return;
        }

        $mimeTypes = [
            'webm' => 'audio/webm',
            'mp4' => 'video/mp4',
            'mpeg' => 'audio/mpeg',
            'mp3' => 'audio/mpeg',
            'wav' => 'audio/wav',
            'ogg' => 'audio/ogg',
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'webp' => 'image/webp',
            'gif' => 'image/gif',
            'pdf' => 'application/pdf',
            'doc' => 'application/msword',
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'xls' => 'application/vnd.ms-excel',
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'ppt' => 'application/vnd.ms-powerpoint',
            'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
            'txt' => 'text/plain',
        ];

        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        $mime = $mimeTypes[$ext] ?? 'application/octet-stream';

        header('Content-Type: ' . $mime);
        header('Content-Length: ' . filesize($filePath));
        header('Cache-Control: public, max-age=31536000');
        header('Accept-Ranges: bytes');
        readfile($filePath);
        exit;
    }
}
