<?php

namespace App\Http\Controllers;

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

class LabelImportController extends Controller
{
    public function __construct(
        private readonly LabelsImportService $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 Labels-Datei ist.',
            ], 422);
        }

        return response()->json([
            'new' => $result->newCount,
            'updated' => $result->updatedCount,
            'total' => $result->totalInFile,
        ]);
    }
}
