<?php

namespace App\Services\Tenancy;

use App\Models\Business;
use App\Models\User;
use Illuminate\Http\Request;

class CurrentBusiness
{
    private ?Business $business = null;

    public function set(?Business $business): void
    {
        $this->business = $business;
    }

    public function get(): ?Business
    {
        return $this->business;
    }

    public function id(): ?int
    {
        return $this->business?->id;
    }

    public function resolveForRequest(Request $request): ?Business
    {
        $user = $request->user();

        if (! $user instanceof User) {
            return null;
        }

        $business = $this->resolveFromSession($request, $user)
            ?? $this->resolveDefaultForUser($user);

        if ($business) {
            $request->session()->put('current_business_id', $business->id);
        }

        $this->set($business);

        return $business;
    }

    private function resolveFromSession(Request $request, User $user): ?Business
    {
        $businessId = $request->session()->get('current_business_id');

        if (! $businessId) {
            return null;
        }

        $business = Business::query()->find($businessId);

        if (! $business || ! $user->canAccessBusiness($business)) {
            $request->session()->forget('current_business_id');

            return null;
        }

        return $business;
    }

    private function resolveDefaultForUser(User $user): ?Business
    {
        if ($user->isSuperAdmin()) {
            return null;
        }

        return $user->ownedBusinesses()->active()->first()
            ?? $user->businesses()->wherePivot('status', 'active')->active()->first();
    }
}
