<?php

declare(strict_types=1);

namespace App\Module\Integration\Infrastructure\Controller;

use App\Module\Integration\Domain\Exception\InvalidPathException;
use App\Module\Integration\Domain\Exception\ShareConnectionException;
use App\Module\Integration\Domain\Exception\ShareNotConfiguredException;
use App\Module\Integration\Domain\Service\FileEntry;
use App\Module\Integration\Domain\Service\FileSource;
use App\Module\Integration\Domain\Service\SharePathResolver;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

class ShareBrowseController extends AbstractController
{
    public function __construct(
        private readonly FileSource $fileSource,
        private readonly SharePathResolver $pathResolver,
    ) {}

    #[Route('/api/share/browse', name: 'share_browse', methods: ['GET'], priority: 1)]
    #[IsGranted('ROLE_USER')]
    public function __invoke(Request $request): JsonResponse
    {
        $rawPath = (string) $request->query->get('path', '');

        try {
            $path = $this->pathResolver->normalizeRelative($rawPath);
        } catch (InvalidPathException) {
            return new JsonResponse(['error' => 'Invalid path.'], 400);
        }

        try {
            $entries = $this->fileSource->dir($path);
        } catch (ShareNotConfiguredException) {
            return new JsonResponse(['error' => 'Share not configured.'], 409);
        } catch (ShareConnectionException) {
            return new JsonResponse(['error' => 'Unable to reach the file share.'], 502);
        }

        return new JsonResponse([
            'path'       => $path,
            'breadcrumb' => $this->breadcrumb($path),
            'entries'    => array_map(static fn (FileEntry $e): array => [
                'name'       => $e->name,
                'path'       => $e->path,
                'isDir'      => $e->isDir,
                'size'       => $e->size,
                'modifiedAt' => $e->modifiedAt,
                'mimeType'   => $e->mimeType,
            ], $entries),
        ]);
    }

    /**
     * @return array<int, array{name: string, path: string}>
     */
    private function breadcrumb(string $path): array
    {
        if ('' === $path) {
            return [];
        }

        $crumbs = [];
        $acc    = '';
        foreach (explode('/', $path) as $segment) {
            $acc      = '' === $acc ? $segment : $acc.'/'.$segment;
            $crumbs[] = ['name' => $segment, 'path' => $acc];
        }

        return $crumbs;
    }
}
