<?php

namespace App\Http\Controllers\Api;

use App\ExportMapRepository;
use App\Http\Controllers\Controller;
use App\Models\ExportMap;
use Illuminate\Support\Str;

class ExportMapApiController extends Controller
{
    public function download(string $uuid)
    {
        $exportMap = ExportMap::where('uuid', $uuid)
            ->where('api_url_enabled', true)
            ->where('active', true)
            ->firstOrFail();

        $exportMap->update(['last_downloaded_at' => now()]);

        $fileName = Str::slug($exportMap->name) . '.' . $exportMap->format;
        $asAttachment = $exportMap->format !== 'json';

        return app()->make(ExportMapRepository::class, ['export_map' => $exportMap])
            ->download($fileName, $asAttachment);
    }
}
