<?php

namespace App\Http\Controllers;

use App\Services\MacrosImportService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Throwable;

class MacroImportController extends Controller
{
    public function __construct(
        private readonly MacrosImportService $importService,
    ) {}

    public function store(Request $request): JsonResponse
    {
        $request->validate(['file' => ['required', 'file', 'max:5120']]);

        $file = $request->file('file');
        $tempPath = $file->getPathname();

        try {
            $result = $this->importService->import($tempPath, $file->getClientOriginalName());
        } catch (Throwable $e) {
            return response()->json([
                'message' => 'Die Datei konnte nicht gelesen werden. Stelle sicher, dass es eine gültige ProPresenter Makro-Datei ist.',
            ], 422);
        }

        return response()->json([
            'stats' => [
                'new' => $result->new,
                'updated' => $result->updated,
                'disabled' => $result->disabled,
                're_enabled' => $result->reEnabled,
            ],
            'warnings' => $result->warnings,
        ]);
    }
}
