<?php

namespace App\Providers;

use App\Tenancy\TenantManager;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(TenantManager::class);
    }

    public function boot(): void
    {
        // Behind a TLS-terminating proxy (Cloudflare → Coolify Traefik → Octane).
        // Force https on URL generation, but DON'T force root URL — each tenant
        // subdomain must keep its own host so Livewire/CSRF work per-tenant.
        if (! $this->app->runningInConsole() && (str_starts_with(config('app.url'), 'https://') || env('FORCE_HTTPS'))) {
            URL::forceScheme('https');
        }

        // Auto-translate labels on every Filament component that has one.
        // Without this, auto-derived labels (e.g. `name` → "Name") bypass __()
        // and always render in English regardless of the app locale.
        foreach ([
            \Filament\Tables\Columns\Column::class,
            \Filament\Tables\Filters\BaseFilter::class,
            \Filament\Forms\Components\Field::class,
            \Filament\Actions\Action::class,
            \Filament\Actions\BulkAction::class,
        ] as $class) {
            if (class_exists($class) && method_exists($class, 'configureUsing')) {
                $class::configureUsing(fn ($c) => method_exists($c, 'translateLabel') ? $c->translateLabel() : $c);
            }
        }
    }
}
