<?php

namespace App\Http\Controllers;

use App\Models\ExportProFile;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class ExportProFileController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'type' => ['required', Rule::in(['prefix', 'postfix', 'keyword'])],
            'keyword' => [Rule::requiredIf(fn () => $request->input('type') === 'keyword'), 'nullable', 'string', 'max:255'],
            'files' => ['required', 'array'],
            'files.*' => ['required', 'file', 'max:10240', 'extensions:pro,probundle'],
        ], [
            'files.*.extensions' => 'Nur .pro- und .probundle-Dateien sind erlaubt.',
        ]);

        $type = $request->input('type');
        $keyword = $type === 'keyword' ? $request->input('keyword') : null;
        $created = [];

        foreach ($request->file('files') as $file) {
            // Store under a random basename but keep the REAL client extension.
            // Laravel's store() names files by the guessed MIME extension, which
            // turns a .probundle (a ZIP) into a .zip and breaks extension-based
            // routing at export time.
            $extension = strtolower($file->getClientOriginalExtension());
            $basename = Str::random(40).($extension !== '' ? '.'.$extension : '');
            $storedPath = $file->storeAs('export-pro-files/'.$type, $basename, 'local');
            $maxOrder = ExportProFile::where('type', $type)->max('order') ?? 0;

            $record = ExportProFile::create([
                'type' => $type,
                'keyword' => $keyword,
                'original_name' => $file->getClientOriginalName(),
                'stored_path' => $storedPath,
                'order' => $maxOrder + 1,
            ]);

            $created[] = [
                'id' => $record->id,
                'original_name' => $record->original_name,
                'order' => $record->order,
            ];
        }

        return response()->json([
            'files' => $created,
            'message' => count($created).' Datei(en) erfolgreich hochgeladen.',
        ], 201);
    }

    public function updateKeyword(Request $request, ExportProFile $exportProFile): JsonResponse
    {
        if ($exportProFile->type !== 'keyword') {
            return response()->json([
                'message' => 'Schlüsselwort kann nur für Schlüsselwort-Dateien geändert werden.',
            ], 422);
        }

        $validated = $request->validate([
            'keyword' => ['required', 'string', 'max:255'],
        ]);

        $exportProFile->update(['keyword' => $validated['keyword']]);

        return response()->json([
            'message' => 'Schlüsselwort erfolgreich aktualisiert.',
        ]);
    }

    public function destroy(ExportProFile $exportProFile): JsonResponse
    {
        Storage::disk('local')->delete($exportProFile->stored_path);
        $exportProFile->delete();

        return response()->json([
            'message' => 'Datei erfolgreich gelöscht.',
        ]);
    }
}
