<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Command;

use Ferienpass\CoreBundle\Entity\Tenant;
use Ferienpass\CoreBundle\Repository\TenantRepository;
use Ferienpass\CoreBundle\Tenant\Surface;
use Ferienpass\CoreBundle\Tenant\TenantContext;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(name: 'ferienpass:tenant:list', description: 'Lists the tenants of this installation')]
class TenantListCommand extends Command
{
    public function __construct(
        private readonly TenantRepository $tenants,
        private readonly TenantContext $tenantContext,
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        if (!$this->tenantContext->isEnabled()) {
            $io->warning('Multi-tenancy is disabled on this build (ferienpass.multi_tenancy.enabled). This installation serves a single Ferienpass.');
        }

        $tenants = $this->tenants->findAllOrdered();
        if ([] === $tenants) {
            $io->info('No tenants defined yet. Create the first one with "ferienpass:tenant:create".');

            return Command::SUCCESS;
        }

        $io->table(
            ['Slug', 'Name', 'Public site', 'Admin', 'Status'],
            array_map(static fn (Tenant $t): array => [
                $t->getSlug(),
                $t->getName(),
                implode("\n", $t->getHostsFor(Surface::Frontend)) ?: '—',
                $t->hasDedicatedAdminHost()
                    ? implode("\n", $t->getHostsFor(Surface::Admin))
                    : implode("\n", array_map(static fn (string $h): string => $h.'/admin', $t->getHostsFor(Surface::Frontend))),
                $t->isDisabled() ? 'disabled' : 'enabled',
            ], $tenants),
        );

        return Command::SUCCESS;
    }
}
