<?php

namespace App\Modules\Admin\Tenancy\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\DTOs\PlanData;
use App\Modules\Admin\Tenancy\Models\Plan;
use App\Modules\Admin\Tenancy\Repositories\ModuleRepository;
use App\Modules\Admin\Tenancy\Requests\StorePlanRequest;
use App\Modules\Admin\Tenancy\Requests\UpdatePlanRequest;
use App\Modules\Admin\Tenancy\Services\PlanService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use RuntimeException;

class PlanController extends Controller
{
    public function __construct(
        private readonly PlanService $service,
        private readonly ModuleRepository $moduleRepository,
    ) {}

    public function index(): View
    {
        return view('pages.admin.plans.index', [
            'plans' => $this->service->list(),
        ]);
    }

    public function create(): View
    {
        return view('pages.admin.plans.create', [
            'modules' => $this->moduleRepository->activeForSelect(),
            'selectedModules' => [],
        ]);
    }

    public function store(StorePlanRequest $request): RedirectResponse
    {
        $this->service->create(PlanData::fromValidated($request->validated()));

        return redirect()
            ->route('admin.plans.index')
            ->with('status', __('plans.created'));
    }

    public function edit(Plan $plan): View
    {
        $plan->load('modules');

        return view('pages.admin.plans.edit', [
            'plan' => $plan,
            'modules' => $this->moduleRepository->activeForSelect(),
            'selectedModules' => $plan->modules->pluck('id')->all(),
        ]);
    }

    public function update(UpdatePlanRequest $request, Plan $plan): RedirectResponse
    {
        $this->service->update($plan, PlanData::fromValidated($request->validated()));

        return redirect()
            ->route('admin.plans.index')
            ->with('status', __('plans.updated'));
    }

    public function destroy(Plan $plan): RedirectResponse
    {
        try {
            $this->service->delete($plan);
        } catch (RuntimeException $exception) {
            return redirect()
                ->route('admin.plans.index')
                ->with('error', $exception->getMessage());
        }

        return redirect()
            ->route('admin.plans.index')
            ->with('status', __('plans.deleted'));
    }
}
