<?php

namespace App\Modules\Admin\Tenancy\Services;

use App\Modules\Admin\Tenancy\DTOs\PlanData;
use App\Modules\Admin\Tenancy\Models\Plan;
use App\Modules\Admin\Tenancy\Repositories\PlanRepository;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use RuntimeException;

class PlanService
{
    public function __construct(
        private readonly PlanRepository $repository,
    ) {}

    public function list(): Collection
    {
        return $this->repository->all();
    }

    public function create(PlanData $data): Plan
    {
        return DB::transaction(function () use ($data) {
            $plan = $this->repository->create($data->toAttributes());
            $this->repository->syncModules($plan, $data->moduleIds);

            if ($data->isDefault) {
                $this->repository->clearDefaultsExcept($plan->id);
            }

            return $plan->load('modules');
        });
    }

    public function update(Plan $plan, PlanData $data): Plan
    {
        return DB::transaction(function () use ($plan, $data) {
            $updated = $this->repository->update($plan, $data->toAttributes());
            $this->repository->syncModules($updated, $data->moduleIds);

            if ($data->isDefault) {
                $this->repository->clearDefaultsExcept($updated->id);
            }

            return $updated->load('modules');
        });
    }

    public function delete(Plan $plan): void
    {
        if ($plan->tenants()->exists()) {
            throw new RuntimeException('Cannot delete a plan that has tenants assigned.');
        }

        $this->repository->delete($plan);
    }
}
