<?php

namespace App\Http\Controllers;

use App\Models\Song;
use App\Services\ProExportService;
use App\Services\ProImportService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class ProFileController extends Controller
{
    public function importPro(Request $request): JsonResponse
    {
        $request->validate([
            'file' => ['required', 'file', 'max:51200'],
        ]);

        $file = $request->file('file');
        $extension = strtolower($file->getClientOriginalExtension());

        if (! in_array($extension, ['pro', 'zip'])) {
            return response()->json([
                'message' => 'Nur .pro und .zip Dateien sind erlaubt.',
            ], 422);
        }

        try {
            $service = new ProImportService;
            $songs = $service->import($file);

            return response()->json([
                'message' => count($songs) === 1
                    ? "Song \"{$songs[0]->title}\" erfolgreich importiert."
                    : count($songs).' Songs erfolgreich importiert.',
                'songs' => collect($songs)->map(fn (Song $song) => [
                    'id' => $song->id,
                    'title' => $song->title,
                    'ccli_id' => $song->ccli_id,
                ]),
            ]);
        } catch (\InvalidArgumentException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        } catch (\RuntimeException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    public function downloadPro(Song $song): BinaryFileResponse
    {
        if ($this->countSongLabels($song) === 0) {
            abort(422, 'Song hat keine Gruppen oder Slides zum Exportieren.');
        }

        $exportService = app(ProExportService::class);
        $tempPath = $exportService->generateProFile($song);

        $filename = preg_replace('/[^a-zA-Z0-9äöüÄÖÜß\-_ ]/', '', $song->title).'.pro';

        return response()->download($tempPath, $filename)->deleteFileAfterSend(true);
    }

    private function countSongLabels(Song $song): int
    {
        return $song->arrangements()
            ->withCount('arrangementLabels')
            ->get()
            ->sum('arrangement_labels_count');
    }
}
