<?php

namespace App\Modules\Admin\Tenancy\Services;

use App\Models\User;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Admin\Tenancy\Repositories\PlanRepository;
use App\Modules\Admin\Tenancy\Repositories\TenantRepository;
use App\Modules\Settings\Rbac\Services\TenantRbacBootstrapService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class TrialService
{
    public function __construct(
        private readonly TenantRepository $tenantRepository,
        private readonly PlanRepository $planRepository,
        private readonly SubscriptionService $subscriptionService,
        private readonly TenantRbacBootstrapService $rbacBootstrap,
    ) {}

    public function provisionFor(User $user): Tenant
    {
        return DB::transaction(function () use ($user) {
            $plan = $this->planRepository->defaultTrial();
            $slug = $this->uniqueSlug($user);

            $tenant = $this->tenantRepository->create([
                'name' => $user->name,
                'slug' => $slug,
                'email' => $user->email,
                'plan_id' => $plan?->id,
                'is_active' => true,
            ]);

            if ($plan) {
                $this->subscriptionService->startFor($tenant, $plan);
            }

            $user->forceFill(['tenant_id' => $tenant->id])->save();
            $this->rbacBootstrap->ensureOwnerRoleAndAssign($tenant, $user);

            return $tenant;
        });
    }

    private function uniqueSlug(User $user): string
    {
        $base = Str::slug($user->name ?: Str::before($user->email, '@')) ?: 'tenant';
        $slug = $base;
        $suffix = 1;

        while ($this->tenantRepository->slugExists($slug)) {
            $slug = $base.'-'.$suffix++;
        }

        return $slug;
    }
}
