<?php

namespace App\Modules\Admin\Tenancy\Services;

use App\Modules\Admin\Tenancy\Models\Plan;
use App\Modules\Admin\Tenancy\Models\Subscription;
use App\Modules\Admin\Tenancy\Models\SubscriptionTransaction;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Admin\Tenancy\Repositories\SubscriptionTransactionRepository;
use App\Modules\Admin\Tenancy\Repositories\TenantRepository;
use Illuminate\Support\Facades\DB;

class UpgradePlanService
{
    public function __construct(
        private readonly SubscriptionService $subscriptionService,
        private readonly SubscriptionTransactionRepository $transactions,
        private readonly TenantRepository $tenants,
    ) {}

    public function upgrade(
        Tenant $tenant,
        Plan $newPlan,
        ?string $paymentMethod = null,
        bool $completeImmediately = true,
    ): Subscription {
        return DB::transaction(function () use (
            $tenant,
            $newPlan,
            $paymentMethod,
            $completeImmediately,
        ): Subscription {
            $txn = $this->transactions->create([
                'tenant_id' => $tenant->id,
                'plan_id' => $newPlan->id,
                'amount' => $newPlan->price,
                'status' => $completeImmediately
                    ? SubscriptionTransaction::STATUS_COMPLETED
                    : SubscriptionTransaction::STATUS_PENDING,
                'payment_method' => $paymentMethod,
                'started_at' => now(),
                'expires_at' => null,
            ]);

            $subscription = $this->subscriptionService->startFor($tenant, $newPlan);

            $this->tenants->update($tenant, ['plan_id' => $newPlan->id]);

            if ($completeImmediately) {
                $this->transactions->update($txn, [
                    'expires_at' => $subscription->ends_at ?? $subscription->trial_ends_at,
                ]);
            }

            return $subscription;
        });
    }
}
