<?php

namespace App\Modules\Admin\Tenancy\Repositories;

use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Support\Lists\ListQuery;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

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

    public function paginateForIndex(Request $request): LengthAwarePaginator
    {
        $query = Tenant::query()->with(['plan', 'activeSubscription.plan']);

        ListQuery::applySearch($query, $request->input('q'), ['name', 'slug', 'email']);
        ListQuery::applyBoolean($query, 'is_active', $request->input('is_active'));
        ListQuery::applyEquals($query, 'plan_id', $request->input('plan_id'));
        ListQuery::applySort(
            $query,
            $request->input('sort'),
            $request->input('dir'),
            [
                'name' => 'name',
                'slug' => 'slug',
                'is_active' => 'is_active',
            ],
            'created_at',
            'desc',
        );

        return ListQuery::paginate($query, $request);
    }

    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();
    }
}
