<?php

namespace App\Modules\Admin\Tenancy\Repositories;

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

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

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