<?php

namespace App\Modules\Admin\Tenancy\Repositories;

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

class PlanRepository
{
    public function all(): Collection
    {
        return Plan::query()
            ->with('modules')
            ->withCount('tenants')
            ->orderBy('name')
            ->get();
    }

    public function paginateForIndex(Request $request): LengthAwarePaginator
    {
        $query = Plan::query()->with('modules')->withCount('tenants');

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

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

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

    public function defaultTrial(): ?Plan
    {
        return Plan::query()->defaultTrial()->first();
    }

    public function findWithModules(int $id): ?Plan
    {
        return Plan::query()->with('modules')->find($id);
    }

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

    public function update(Plan $plan, array $data): Plan
    {
        $plan->update($data);

        return $plan->fresh();
    }

    public function syncModules(Plan $plan, array $moduleIds): void
    {
        $plan->modules()->sync($moduleIds);
    }

    public function clearDefaultsExcept(int $excludeId): void
    {
        Plan::query()->where('id', '!=', $excludeId)->update(['is_default' => false]);
    }

    public function delete(Plan $plan): void
    {
        $plan->delete();
    }
}
