<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class AdminKycDocumentDownloadController extends Controller
{
    /**
     * Descarga archivos del expediente KYC desde el disco privado `kyc` (solo administradores).
     *
     * @param  'front'|'back'|'selfie'  $document
     */
    public function __invoke(Request $request, User $user, string $document): StreamedResponse
    {
        abort_if($request->user()?->is_admin !== true, 403);
        abort_unless(! $user->is_admin, 404);

        $profile = $user->kycProfile;
        abort_if($profile === null, 404);

        $column = match ($document) {
            'front' => 'document_front_path',
            'back' => 'document_back_path',
            'selfie' => 'selfie_document_path',
            default => abort(404),
        };

        $relativePath = $profile->{$column};
        abort_if($relativePath === null || $relativePath === '', 404);

        $disk = Storage::disk('kyc');
        abort_unless($disk->exists($relativePath), 404);

        $extRaw = strtolower((string) pathinfo($relativePath, PATHINFO_EXTENSION));
        $extension = preg_match('/^[a-z0-9]{1,8}$/', $extRaw) === 1 ? $extRaw : 'bin';

        $label = match ($document) {
            'front' => 'frontal',
            'back' => 'reverso',
            'selfie' => 'selfie',
            default => 'documento',
        };

        return $disk->download(
            $relativePath,
            sprintf('kyc-usuario-%d-%s.%s', $user->id, $label, $extension),
        );
    }
}
