<?php

namespace App\Modules\Admin\Tenancy\Repositories;

use App\Modules\Admin\Tenancy\Models\Tenant;
use Illuminate\Database\Eloquent\Collection;

class TenantRepository
{
    public function all(): Collection
    {
        return Tenant::query()
            ->with(['plan', 'activeSubscription.plan'])
            ->orderByDesc('created_at')
            ->get();
    }

    public function findWithPlan(int $id): ?Tenant
    {
        return Tenant::query()->with(['plan', 'activeSubscription.plan'])->find($id);
    }

    public function create(array $data): Tenant
    {
        return Tenant::query()->create($data);
    }

    public function update(Tenant $tenant, array $data): Tenant
    {
        $tenant->update($data);

        return $tenant->fresh(['plan', 'activeSubscription.plan']);
    }

    public function delete(Tenant $tenant): void
    {
        $tenant->delete();
    }

    public function slugExists(string $slug): bool
    {
        return Tenant::query()->where('slug', $slug)->exists();
    }

    /**
     * @return array<int, string>
     */
    public function idNamePairsOrdered(): array
    {
        return Tenant::query()
            ->orderBy('name')
            ->pluck('name', 'id')
            ->all();
    }
}
