<?php

declare(strict_types=1);

namespace ImovelZapAi\Publishing\Presentation\Http\Controllers\Web;

use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use ImovelZapAi\Publishing\Application\Actions\UpdateTenantPublishingConfigurationAction;
use ImovelZapAi\Publishing\Application\Services\TenantPublishingConfigResolver;
use ImovelZapAi\Publishing\Domain\Enums\TenantPublishingPlan;
use ImovelZapAi\Publishing\Domain\Enums\TenantPublishingStatus;
use ImovelZapAi\Publishing\Presentation\Http\Requests\TenantPublishingConfigurationRequest;
use ImovelZapAi\Tenancy\Infrastructure\Persistence\Eloquent\TenantModel;
use ImovelZapAi\Tenancy\Support\TenantContext;

final class TenantPublishingConfigurationController
{
    public function __construct(
        private readonly TenantPublishingConfigResolver $configResolver,
    ) {}

    public function edit(): View
    {
        $tenant = $this->currentTenant();
        $config = $this->configResolver->forTenant((string) $tenant->id);

        return view('publishing.configuration', [
            'config' => $config,
            'statuses' => TenantPublishingStatus::cases(),
            'plans' => TenantPublishingPlan::cases(),
            'canEdit' => auth()->user()?->hasAnyRole(['Admin', 'Gestor']) ?? false,
        ]);
    }

    public function update(
        TenantPublishingConfigurationRequest $request,
        UpdateTenantPublishingConfigurationAction $action,
    ): RedirectResponse {
        $tenant = $this->currentTenant();

        $action->execute($tenant, $request->validated());

        return redirect()
            ->route('publishing.config.edit')
            ->with('status', 'Configuração de publicação atualizada.');
    }

    private function currentTenant(): TenantModel
    {
        $tenantId = TenantContext::id();

        abort_if($tenantId === null, 403);

        return TenantModel::query()->whereKey($tenantId)->firstOrFail();
    }
}
