<?php

namespace App\Http\Controllers;

use App\Models\ArtigoAnexo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class WikiMediaController extends Controller
{
    public function anexo(Request $request, ArtigoAnexo $anexo): BinaryFileResponse
    {
        $artigo = $anexo->artigo()->withTrashed()->firstOrFail();
        $usuario = $request->user();

        abort_unless($usuario?->can('wiki.visualizar'), 403);
        abort_if($artigo->trashed(), 404);
        abort_if($artigo->restrito && ! $usuario->hasRole('Administrador Master') && (int) $usuario->departamento_id !== (int) $artigo->departamento_id, 403);
        abort_if($artigo->status !== 'publicado' && ! $usuario->can('wiki.editar'), 403);
        abort_unless(Storage::disk('public')->exists($anexo->caminho), 404);

        return $this->responderArquivo($anexo->caminho, $anexo->nome_original, $anexo->mime);
    }

    public function editor(Request $request, string $path): BinaryFileResponse
    {
        abort_unless($request->user()?->can('wiki.visualizar'), 403);
        abort_unless(Str::startsWith($path, 'wiki/editor/'), 404);
        abort_unless(Storage::disk('public')->exists($path), 404);

        return $this->responderArquivo($path);
    }

    private function responderArquivo(string $caminho, ?string $nomeOriginal = null, ?string $mime = null): BinaryFileResponse
    {
        $arquivo = Storage::disk('public')->path($caminho);
        $nome = $nomeOriginal ?: basename($caminho);
        $headers = [
            'Content-Type' => $mime ?: (mime_content_type($arquivo) ?: 'application/octet-stream'),
            'Content-Disposition' => 'inline; filename="' . str_replace('"', '', $nome) . '"',
            'X-Content-Type-Options' => 'nosniff',
        ];

        return response()->file($arquivo, $headers);
    }
}
