<?php

namespace App\Modules\Admin\Tenancy\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\DTOs\TenantData;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Admin\Tenancy\Repositories\PlanRepository;
use App\Modules\Admin\Tenancy\Requests\StoreTenantRequest;
use App\Modules\Admin\Tenancy\Requests\UpdateTenantRequest;
use App\Modules\Admin\Tenancy\Services\ModuleAccessService;
use App\Modules\Admin\Tenancy\Services\TenantService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class TenantController extends Controller
{
    public function __construct(
        private readonly TenantService $service,
        private readonly PlanRepository $planRepository,
        private readonly ModuleAccessService $accessService,
    ) {}

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

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

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

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

    public function edit(Tenant $tenant): View
    {
        return view('pages.admin.tenants.edit', [
            'tenant' => $tenant,
            'plans' => $this->planRepository->activeForSelect(),
        ]);
    }

    public function update(UpdateTenantRequest $request, Tenant $tenant): RedirectResponse
    {
        $updated = $this->service->update($tenant, TenantData::fromValidated($request->validated()));
        $this->accessService->forgetTenant($updated);

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

    public function destroy(Tenant $tenant): RedirectResponse
    {
        $this->accessService->forgetTenant($tenant);
        $this->service->delete($tenant);

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